babylon.max.js 4.4 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732867338673486735867368673786738867398674086741867428674386744867458674686747867488674986750867518675286753867548675586756867578675886759867608676186762867638676486765867668676786768867698677086771867728677386774867758677686777867788677986780867818678286783867848678586786867878678886789867908679186792867938679486795867968679786798867998680086801868028680386804868058680686807868088680986810868118681286813868148681586816868178681886819868208682186822868238682486825868268682786828868298683086831868328683386834868358683686837868388683986840868418684286843868448684586846868478684886849868508685186852868538685486855868568685786858868598686086861868628686386864868658686686867868688686986870868718687286873868748687586876868778687886879868808688186882868838688486885868868688786888868898689086891868928689386894868958689686897868988689986900869018690286903869048690586906869078690886909869108691186912869138691486915869168691786918869198692086921869228692386924869258692686927869288692986930869318693286933869348693586936869378693886939869408694186942869438694486945869468694786948869498695086951869528695386954869558695686957869588695986960869618696286963869648696586966869678696886969869708697186972869738697486975869768697786978869798698086981869828698386984869858698686987869888698986990869918699286993869948699586996869978699886999870008700187002870038700487005870068700787008870098701087011870128701387014870158701687017870188701987020870218702287023870248702587026870278702887029870308703187032870338703487035870368703787038870398704087041870428704387044870458704687047870488704987050870518705287053870548705587056870578705887059870608706187062870638706487065870668706787068870698707087071870728707387074870758707687077870788707987080870818708287083870848708587086870878708887089870908709187092870938709487095870968709787098870998710087101871028710387104871058710687107871088710987110871118711287113871148711587116871178711887119871208712187122871238712487125871268712787128871298713087131871328713387134871358713687137871388713987140871418714287143871448714587146871478714887149871508715187152871538715487155871568715787158871598716087161871628716387164871658716687167871688716987170871718717287173871748717587176871778717887179871808718187182871838718487185871868718787188871898719087191871928719387194871958719687197871988719987200872018720287203872048720587206872078720887209872108721187212872138721487215872168721787218872198722087221872228722387224872258722687227872288722987230872318723287233872348723587236872378723887239872408724187242872438724487245872468724787248872498725087251872528725387254872558725687257872588725987260872618726287263872648726587266872678726887269872708727187272872738727487275872768727787278872798728087281872828728387284872858728687287872888728987290872918729287293872948729587296872978729887299873008730187302873038730487305873068730787308873098731087311873128731387314873158731687317873188731987320873218732287323873248732587326873278732887329873308733187332873338733487335873368733787338873398734087341873428734387344873458734687347873488734987350873518735287353873548735587356873578735887359873608736187362873638736487365873668736787368873698737087371873728737387374873758737687377873788737987380873818738287383873848738587386873878738887389873908739187392873938739487395873968739787398873998740087401874028740387404874058740687407874088740987410874118741287413874148741587416874178741887419874208742187422874238742487425874268742787428874298743087431874328743387434874358743687437874388743987440874418744287443874448744587446874478744887449874508745187452874538745487455874568745787458874598746087461874628746387464874658746687467874688746987470874718747287473874748747587476874778747887479874808748187482874838748487485874868748787488874898749087491874928749387494874958749687497874988749987500875018750287503875048750587506875078750887509875108751187512875138751487515875168751787518875198752087521875228752387524875258752687527875288752987530875318753287533875348753587536875378753887539875408754187542875438754487545875468754787548875498755087551875528755387554875558755687557875588755987560875618756287563875648756587566875678756887569875708757187572875738757487575875768757787578875798758087581875828758387584875858758687587875888758987590875918759287593875948759587596875978759887599876008760187602876038760487605876068760787608876098761087611876128761387614876158761687617876188761987620876218762287623876248762587626876278762887629876308763187632876338763487635876368763787638876398764087641876428764387644876458764687647876488764987650876518765287653876548765587656876578765887659876608766187662876638766487665876668766787668876698767087671876728767387674876758767687677876788767987680876818768287683876848768587686876878768887689876908769187692876938769487695876968769787698876998770087701877028770387704877058770687707877088770987710877118771287713877148771587716877178771887719877208772187722877238772487725877268772787728877298773087731877328773387734877358773687737877388773987740877418774287743877448774587746877478774887749877508775187752877538775487755877568775787758877598776087761877628776387764877658776687767877688776987770877718777287773877748777587776877778777887779877808778187782877838778487785877868778787788877898779087791877928779387794877958779687797877988779987800878018780287803878048780587806878078780887809878108781187812878138781487815878168781787818878198782087821878228782387824878258782687827878288782987830878318783287833878348783587836878378783887839878408784187842878438784487845878468784787848878498785087851878528785387854878558785687857878588785987860878618786287863878648786587866878678786887869878708787187872878738787487875878768787787878878798788087881878828788387884878858788687887878888788987890878918789287893878948789587896878978789887899879008790187902879038790487905879068790787908879098791087911879128791387914879158791687917879188791987920879218792287923879248792587926879278792887929879308793187932879338793487935879368793787938879398794087941879428794387944879458794687947879488794987950879518795287953879548795587956879578795887959879608796187962879638796487965879668796787968879698797087971879728797387974879758797687977879788797987980879818798287983879848798587986879878798887989879908799187992879938799487995879968799787998879998800088001880028800388004880058800688007880088800988010880118801288013880148801588016880178801888019880208802188022880238802488025880268802788028880298803088031880328803388034880358803688037880388803988040880418804288043880448804588046880478804888049880508805188052880538805488055880568805788058880598806088061880628806388064880658806688067880688806988070880718807288073880748807588076880778807888079880808808188082880838808488085880868808788088880898809088091880928809388094880958809688097880988809988100881018810288103881048810588106881078810888109881108811188112881138811488115881168811788118881198812088121881228812388124881258812688127881288812988130881318813288133881348813588136881378813888139881408814188142881438814488145881468814788148881498815088151881528815388154881558815688157881588815988160881618816288163881648816588166881678816888169881708817188172881738817488175881768817788178881798818088181881828818388184881858818688187881888818988190881918819288193881948819588196881978819888199882008820188202882038820488205882068820788208882098821088211882128821388214882158821688217882188821988220882218822288223882248822588226882278822888229882308823188232882338823488235882368823788238882398824088241882428824388244882458824688247882488824988250882518825288253882548825588256882578825888259882608826188262882638826488265882668826788268882698827088271882728827388274882758827688277882788827988280882818828288283882848828588286882878828888289882908829188292882938829488295882968829788298882998830088301883028830388304883058830688307883088830988310883118831288313883148831588316883178831888319883208832188322883238832488325883268832788328883298833088331883328833388334883358833688337883388833988340883418834288343883448834588346883478834888349883508835188352883538835488355883568835788358883598836088361883628836388364883658836688367883688836988370883718837288373883748837588376883778837888379883808838188382883838838488385883868838788388883898839088391883928839388394883958839688397883988839988400884018840288403884048840588406884078840888409884108841188412884138841488415884168841788418884198842088421884228842388424884258842688427884288842988430884318843288433884348843588436884378843888439884408844188442884438844488445884468844788448884498845088451884528845388454884558845688457884588845988460884618846288463884648846588466884678846888469884708847188472884738847488475884768847788478884798848088481884828848388484884858848688487884888848988490884918849288493884948849588496884978849888499885008850188502885038850488505885068850788508885098851088511885128851388514885158851688517885188851988520885218852288523885248852588526885278852888529885308853188532885338853488535885368853788538885398854088541885428854388544885458854688547885488854988550885518855288553885548855588556885578855888559885608856188562885638856488565885668856788568885698857088571885728857388574885758857688577885788857988580885818858288583885848858588586885878858888589885908859188592885938859488595885968859788598885998860088601886028860388604886058860688607886088860988610886118861288613886148861588616886178861888619886208862188622886238862488625886268862788628886298863088631886328863388634886358863688637886388863988640886418864288643886448864588646886478864888649886508865188652886538865488655886568865788658886598866088661886628866388664886658866688667886688866988670886718867288673886748867588676886778867888679886808868188682886838868488685886868868788688886898869088691886928869388694886958869688697886988869988700887018870288703887048870588706887078870888709887108871188712887138871488715887168871788718887198872088721887228872388724887258872688727887288872988730887318873288733887348873588736887378873888739887408874188742887438874488745887468874788748887498875088751887528875388754887558875688757887588875988760887618876288763887648876588766887678876888769887708877188772887738877488775887768877788778887798878088781887828878388784887858878688787887888878988790887918879288793887948879588796887978879888799888008880188802888038880488805888068880788808888098881088811888128881388814888158881688817888188881988820888218882288823888248882588826888278882888829888308883188832888338883488835888368883788838888398884088841888428884388844888458884688847888488884988850888518885288853888548885588856888578885888859888608886188862888638886488865888668886788868888698887088871888728887388874888758887688877888788887988880888818888288883888848888588886888878888888889888908889188892888938889488895888968889788898888998890088901889028890388904889058890688907889088890988910889118891288913889148891588916889178891888919889208892188922889238892488925889268892788928889298893088931889328893388934889358893688937889388893988940889418894288943889448894588946889478894888949889508895188952889538895488955889568895788958889598896088961889628896388964889658896688967889688896988970889718897288973889748897588976889778897888979889808898188982889838898488985889868898788988889898899088991889928899388994889958899688997889988899989000890018900289003890048900589006890078900889009890108901189012890138901489015890168901789018890198902089021890228902389024890258902689027890288902989030890318903289033890348903589036890378903889039890408904189042890438904489045890468904789048890498905089051890528905389054890558905689057890588905989060890618906289063890648906589066890678906889069890708907189072890738907489075890768907789078890798908089081890828908389084890858908689087890888908989090890918909289093890948909589096890978909889099891008910189102891038910489105891068910789108891098911089111891128911389114891158911689117891188911989120891218912289123891248912589126891278912889129891308913189132891338913489135891368913789138891398914089141891428914389144891458914689147891488914989150891518915289153891548915589156891578915889159891608916189162891638916489165891668916789168891698917089171891728917389174891758917689177891788917989180891818918289183891848918589186891878918889189891908919189192891938919489195891968919789198891998920089201892028920389204892058920689207892088920989210892118921289213892148921589216892178921889219892208922189222892238922489225892268922789228892298923089231892328923389234892358923689237892388923989240892418924289243892448924589246892478924889249892508925189252892538925489255892568925789258892598926089261892628926389264892658926689267892688926989270892718927289273892748927589276892778927889279892808928189282892838928489285892868928789288892898929089291892928929389294892958929689297892988929989300893018930289303893048930589306893078930889309893108931189312893138931489315893168931789318893198932089321893228932389324893258932689327893288932989330893318933289333893348933589336893378933889339893408934189342893438934489345893468934789348893498935089351893528935389354893558935689357893588935989360893618936289363893648936589366893678936889369893708937189372893738937489375893768937789378893798938089381893828938389384893858938689387893888938989390893918939289393893948939589396893978939889399894008940189402894038940489405894068940789408894098941089411894128941389414894158941689417894188941989420894218942289423894248942589426894278942889429894308943189432894338943489435894368943789438894398944089441894428944389444894458944689447894488944989450894518945289453894548945589456894578945889459894608946189462894638946489465894668946789468894698947089471894728947389474894758947689477894788947989480894818948289483894848948589486894878948889489894908949189492894938949489495894968949789498894998950089501895028950389504895058950689507895088950989510895118951289513895148951589516895178951889519895208952189522895238952489525895268952789528895298953089531895328953389534895358953689537895388953989540895418954289543895448954589546895478954889549895508955189552895538955489555895568955789558895598956089561895628956389564895658956689567895688956989570895718957289573895748957589576895778957889579895808958189582895838958489585895868958789588895898959089591895928959389594895958959689597895988959989600896018960289603896048960589606896078960889609896108961189612896138961489615896168961789618896198962089621896228962389624896258962689627896288962989630896318963289633896348963589636896378963889639896408964189642896438964489645896468964789648896498965089651896528965389654896558965689657896588965989660896618966289663896648966589666896678966889669896708967189672896738967489675896768967789678896798968089681896828968389684896858968689687896888968989690896918969289693896948969589696896978969889699897008970189702897038970489705897068970789708897098971089711897128971389714897158971689717897188971989720897218972289723897248972589726897278972889729897308973189732897338973489735897368973789738897398974089741897428974389744897458974689747897488974989750897518975289753897548975589756897578975889759897608976189762897638976489765897668976789768897698977089771897728977389774897758977689777897788977989780897818978289783897848978589786897878978889789897908979189792897938979489795897968979789798897998980089801898028980389804898058980689807898088980989810898118981289813898148981589816898178981889819898208982189822898238982489825898268982789828898298983089831898328983389834898358983689837898388983989840898418984289843898448984589846898478984889849898508985189852898538985489855898568985789858898598986089861898628986389864898658986689867898688986989870898718987289873898748987589876898778987889879898808988189882898838988489885898868988789888898898989089891898928989389894898958989689897898988989989900899018990289903899048990589906899078990889909899108991189912899138991489915899168991789918899198992089921899228992389924899258992689927899288992989930899318993289933899348993589936899378993889939899408994189942899438994489945899468994789948899498995089951899528995389954899558995689957899588995989960899618996289963899648996589966899678996889969899708997189972899738997489975899768997789978899798998089981899828998389984899858998689987899888998989990899918999289993899948999589996899978999889999900009000190002900039000490005900069000790008900099001090011900129001390014900159001690017900189001990020900219002290023900249002590026900279002890029900309003190032900339003490035900369003790038900399004090041900429004390044900459004690047900489004990050900519005290053900549005590056900579005890059900609006190062900639006490065900669006790068900699007090071900729007390074900759007690077900789007990080900819008290083900849008590086900879008890089900909009190092900939009490095900969009790098900999010090101901029010390104901059010690107901089010990110901119011290113901149011590116901179011890119901209012190122901239012490125901269012790128901299013090131901329013390134901359013690137901389013990140901419014290143901449014590146901479014890149901509015190152901539015490155901569015790158901599016090161901629016390164901659016690167901689016990170901719017290173901749017590176901779017890179901809018190182901839018490185901869018790188901899019090191901929019390194901959019690197901989019990200902019020290203902049020590206902079020890209902109021190212902139021490215902169021790218902199022090221902229022390224902259022690227902289022990230902319023290233902349023590236902379023890239902409024190242902439024490245902469024790248902499025090251902529025390254902559025690257902589025990260902619026290263902649026590266902679026890269902709027190272902739027490275902769027790278902799028090281902829028390284902859028690287902889028990290902919029290293902949029590296902979029890299903009030190302903039030490305903069030790308903099031090311903129031390314903159031690317903189031990320903219032290323903249032590326903279032890329903309033190332903339033490335903369033790338903399034090341903429034390344903459034690347903489034990350903519035290353903549035590356903579035890359903609036190362903639036490365903669036790368903699037090371903729037390374903759037690377903789037990380903819038290383903849038590386903879038890389903909039190392903939039490395903969039790398903999040090401904029040390404904059040690407904089040990410904119041290413904149041590416904179041890419904209042190422904239042490425904269042790428904299043090431904329043390434904359043690437904389043990440904419044290443904449044590446904479044890449904509045190452904539045490455904569045790458904599046090461904629046390464904659046690467904689046990470904719047290473904749047590476904779047890479904809048190482904839048490485904869048790488904899049090491904929049390494904959049690497904989049990500905019050290503905049050590506905079050890509905109051190512905139051490515905169051790518905199052090521905229052390524905259052690527905289052990530905319053290533905349053590536905379053890539905409054190542905439054490545905469054790548905499055090551905529055390554905559055690557905589055990560905619056290563905649056590566905679056890569905709057190572905739057490575905769057790578905799058090581905829058390584905859058690587905889058990590905919059290593905949059590596905979059890599906009060190602906039060490605906069060790608906099061090611906129061390614906159061690617906189061990620906219062290623906249062590626906279062890629906309063190632906339063490635906369063790638906399064090641906429064390644906459064690647906489064990650906519065290653906549065590656906579065890659906609066190662906639066490665906669066790668906699067090671906729067390674906759067690677906789067990680906819068290683906849068590686906879068890689906909069190692906939069490695906969069790698906999070090701907029070390704907059070690707907089070990710907119071290713907149071590716907179071890719907209072190722907239072490725907269072790728907299073090731907329073390734907359073690737907389073990740907419074290743907449074590746907479074890749907509075190752907539075490755907569075790758907599076090761907629076390764907659076690767907689076990770907719077290773907749077590776907779077890779907809078190782907839078490785907869078790788907899079090791907929079390794907959079690797907989079990800908019080290803908049080590806908079080890809908109081190812908139081490815908169081790818908199082090821908229082390824908259082690827908289082990830908319083290833908349083590836908379083890839908409084190842908439084490845908469084790848908499085090851908529085390854908559085690857908589085990860908619086290863908649086590866908679086890869908709087190872908739087490875908769087790878908799088090881908829088390884908859088690887908889088990890908919089290893908949089590896908979089890899909009090190902909039090490905909069090790908909099091090911909129091390914909159091690917909189091990920909219092290923909249092590926909279092890929909309093190932909339093490935909369093790938909399094090941909429094390944909459094690947909489094990950909519095290953909549095590956909579095890959909609096190962909639096490965909669096790968909699097090971909729097390974909759097690977909789097990980909819098290983909849098590986909879098890989909909099190992909939099490995909969099790998909999100091001910029100391004910059100691007910089100991010910119101291013910149101591016910179101891019910209102191022910239102491025910269102791028910299103091031910329103391034910359103691037910389103991040910419104291043910449104591046910479104891049910509105191052910539105491055910569105791058910599106091061910629106391064910659106691067910689106991070910719107291073910749107591076910779107891079910809108191082910839108491085910869108791088910899109091091910929109391094910959109691097910989109991100911019110291103911049110591106911079110891109911109111191112911139111491115911169111791118911199112091121911229112391124911259112691127911289112991130911319113291133911349113591136911379113891139911409114191142911439114491145911469114791148911499115091151911529115391154911559115691157911589115991160911619116291163911649116591166911679116891169911709117191172911739117491175911769117791178911799118091181911829118391184911859118691187911889118991190911919119291193911949119591196911979119891199912009120191202912039120491205912069120791208912099121091211912129121391214912159121691217912189121991220912219122291223912249122591226912279122891229912309123191232912339123491235912369123791238912399124091241912429124391244912459124691247912489124991250912519125291253912549125591256912579125891259912609126191262912639126491265912669126791268912699127091271912729127391274912759127691277912789127991280912819128291283912849128591286912879128891289912909129191292912939129491295912969129791298912999130091301913029130391304913059130691307913089130991310913119131291313913149131591316913179131891319913209132191322913239132491325913269132791328913299133091331913329133391334913359133691337913389133991340913419134291343913449134591346913479134891349913509135191352913539135491355913569135791358913599136091361913629136391364913659136691367913689136991370913719137291373913749137591376913779137891379913809138191382913839138491385913869138791388913899139091391913929139391394913959139691397913989139991400914019140291403914049140591406914079140891409914109141191412914139141491415914169141791418914199142091421914229142391424914259142691427914289142991430914319143291433914349143591436914379143891439914409144191442914439144491445914469144791448914499145091451914529145391454914559145691457914589145991460914619146291463914649146591466914679146891469914709147191472914739147491475914769147791478914799148091481914829148391484914859148691487914889148991490914919149291493914949149591496914979149891499915009150191502915039150491505915069150791508915099151091511915129151391514915159151691517915189151991520915219152291523915249152591526915279152891529915309153191532915339153491535915369153791538915399154091541915429154391544915459154691547915489154991550915519155291553915549155591556915579155891559915609156191562915639156491565915669156791568915699157091571915729157391574915759157691577915789157991580915819158291583915849158591586915879158891589915909159191592915939159491595915969159791598915999160091601916029160391604916059160691607916089160991610916119161291613916149161591616916179161891619916209162191622916239162491625916269162791628916299163091631916329163391634916359163691637916389163991640916419164291643916449164591646916479164891649916509165191652916539165491655916569165791658916599166091661916629166391664916659166691667916689166991670916719167291673916749167591676916779167891679916809168191682916839168491685916869168791688916899169091691916929169391694916959169691697916989169991700917019170291703917049170591706917079170891709917109171191712917139171491715917169171791718917199172091721917229172391724917259172691727917289172991730917319173291733917349173591736917379173891739917409174191742917439174491745917469174791748917499175091751917529175391754917559175691757917589175991760917619176291763917649176591766917679176891769917709177191772917739177491775917769177791778917799178091781917829178391784917859178691787917889178991790917919179291793917949179591796917979179891799918009180191802918039180491805918069180791808918099181091811918129181391814918159181691817918189181991820918219182291823918249182591826918279182891829918309183191832918339183491835918369183791838918399184091841918429184391844918459184691847918489184991850918519185291853918549185591856918579185891859918609186191862918639186491865918669186791868918699187091871918729187391874918759187691877918789187991880918819188291883918849188591886918879188891889918909189191892918939189491895918969189791898918999190091901919029190391904919059190691907919089190991910919119191291913919149191591916919179191891919919209192191922919239192491925919269192791928919299193091931919329193391934919359193691937919389193991940919419194291943919449194591946919479194891949919509195191952919539195491955919569195791958919599196091961919629196391964919659196691967919689196991970919719197291973919749197591976919779197891979919809198191982919839198491985919869198791988919899199091991919929199391994919959199691997919989199992000920019200292003920049200592006920079200892009920109201192012920139201492015920169201792018920199202092021920229202392024920259202692027920289202992030920319203292033920349203592036920379203892039920409204192042920439204492045920469204792048920499205092051920529205392054920559205692057920589205992060920619206292063920649206592066920679206892069920709207192072920739207492075920769207792078920799208092081920829208392084920859208692087920889208992090920919209292093920949209592096920979209892099921009210192102921039210492105921069210792108921099211092111921129211392114921159211692117921189211992120921219212292123921249212592126921279212892129921309213192132921339213492135921369213792138921399214092141921429214392144921459214692147921489214992150921519215292153921549215592156921579215892159921609216192162921639216492165921669216792168921699217092171921729217392174921759217692177921789217992180921819218292183921849218592186921879218892189921909219192192921939219492195921969219792198921999220092201922029220392204922059220692207922089220992210922119221292213922149221592216922179221892219922209222192222922239222492225922269222792228922299223092231922329223392234922359223692237922389223992240922419224292243922449224592246922479224892249922509225192252922539225492255922569225792258922599226092261922629226392264922659226692267922689226992270922719227292273922749227592276922779227892279922809228192282922839228492285922869228792288922899229092291922929229392294922959229692297922989229992300923019230292303923049230592306923079230892309923109231192312923139231492315923169231792318923199232092321923229232392324923259232692327923289232992330923319233292333923349233592336923379233892339923409234192342923439234492345923469234792348923499235092351923529235392354923559235692357923589235992360923619236292363923649236592366923679236892369923709237192372923739237492375923769237792378923799238092381923829238392384923859238692387923889238992390923919239292393923949239592396923979239892399924009240192402924039240492405924069240792408924099241092411924129241392414924159241692417924189241992420924219242292423924249242592426924279242892429924309243192432924339243492435924369243792438924399244092441924429244392444924459244692447924489244992450924519245292453924549245592456924579245892459924609246192462924639246492465924669246792468924699247092471924729247392474924759247692477924789247992480924819248292483924849248592486924879248892489924909249192492924939249492495924969249792498924999250092501925029250392504925059250692507925089250992510925119251292513925149251592516925179251892519925209252192522925239252492525925269252792528925299253092531925329253392534925359253692537925389253992540925419254292543925449254592546925479254892549925509255192552925539255492555925569255792558925599256092561925629256392564925659256692567925689256992570925719257292573925749257592576925779257892579925809258192582925839258492585925869258792588925899259092591925929259392594925959259692597925989259992600926019260292603926049260592606926079260892609926109261192612926139261492615926169261792618926199262092621926229262392624926259262692627926289262992630926319263292633926349263592636926379263892639926409264192642926439264492645926469264792648926499265092651926529265392654926559265692657926589265992660
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. (function universalModuleDefinition(root, factory) {
  18. if(typeof exports === 'object' && typeof module === 'object')
  19. module.exports = factory();
  20. else if(typeof define === 'function' && define.amd)
  21. define("babylonjs", [], factory);
  22. else if(typeof exports === 'object')
  23. exports["babylonjs"] = factory();
  24. else {
  25. root["BABYLON"] = factory(root["BABYLON"]);
  26. }
  27. })(this, function() {
  28. var BABYLON;
  29. (function (BABYLON) {
  30. /**
  31. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  32. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  33. */
  34. var EffectFallbacks = /** @class */ (function () {
  35. function EffectFallbacks() {
  36. this._defines = {};
  37. this._currentRank = 32;
  38. this._maxRank = -1;
  39. }
  40. /**
  41. * Removes the fallback from the bound mesh.
  42. */
  43. EffectFallbacks.prototype.unBindMesh = function () {
  44. this._mesh = null;
  45. };
  46. /**
  47. * Adds a fallback on the specified property.
  48. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  49. * @param define The name of the define in the shader
  50. */
  51. EffectFallbacks.prototype.addFallback = function (rank, define) {
  52. if (!this._defines[rank]) {
  53. if (rank < this._currentRank) {
  54. this._currentRank = rank;
  55. }
  56. if (rank > this._maxRank) {
  57. this._maxRank = rank;
  58. }
  59. this._defines[rank] = new Array();
  60. }
  61. this._defines[rank].push(define);
  62. };
  63. /**
  64. * Sets the mesh to use CPU skinning when needing to fallback.
  65. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  66. * @param mesh The mesh to use the fallbacks.
  67. */
  68. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  69. this._mesh = mesh;
  70. if (rank < this._currentRank) {
  71. this._currentRank = rank;
  72. }
  73. if (rank > this._maxRank) {
  74. this._maxRank = rank;
  75. }
  76. };
  77. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  78. /**
  79. * Checks to see if more fallbacks are still availible.
  80. */
  81. get: function () {
  82. return this._currentRank <= this._maxRank;
  83. },
  84. enumerable: true,
  85. configurable: true
  86. });
  87. /**
  88. * Removes the defines that shoould be removed when falling back.
  89. * @param currentDefines defines the current define statements for the shader.
  90. * @param effect defines the current effect we try to compile
  91. * @returns The resulting defines with defines of the current rank removed.
  92. */
  93. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  94. // First we try to switch to CPU skinning
  95. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  96. this._mesh.computeBonesUsingShaders = false;
  97. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  98. var scene = this._mesh.getScene();
  99. for (var index = 0; index < scene.meshes.length; index++) {
  100. var otherMesh = scene.meshes[index];
  101. if (!otherMesh.material) {
  102. continue;
  103. }
  104. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  105. continue;
  106. }
  107. if (otherMesh.material.getEffect() === effect) {
  108. otherMesh.computeBonesUsingShaders = false;
  109. }
  110. else {
  111. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  112. var subMesh = _a[_i];
  113. var subMeshEffect = subMesh.effect;
  114. if (subMeshEffect === effect) {
  115. otherMesh.computeBonesUsingShaders = false;
  116. break;
  117. }
  118. }
  119. }
  120. }
  121. }
  122. else {
  123. var currentFallbacks = this._defines[this._currentRank];
  124. if (currentFallbacks) {
  125. for (var index = 0; index < currentFallbacks.length; index++) {
  126. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  127. }
  128. }
  129. this._currentRank++;
  130. }
  131. return currentDefines;
  132. };
  133. return EffectFallbacks;
  134. }());
  135. BABYLON.EffectFallbacks = EffectFallbacks;
  136. /**
  137. * Options to be used when creating an effect.
  138. */
  139. var EffectCreationOptions = /** @class */ (function () {
  140. function EffectCreationOptions() {
  141. }
  142. return EffectCreationOptions;
  143. }());
  144. BABYLON.EffectCreationOptions = EffectCreationOptions;
  145. /**
  146. * Effect containing vertex and fragment shader that can be executed on an object.
  147. */
  148. var Effect = /** @class */ (function () {
  149. /**
  150. * Instantiates an effect.
  151. * An effect can be used to create/manage/execute vertex and fragment shaders.
  152. * @param baseName Name of the effect.
  153. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  154. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  155. * @param samplers List of sampler variables that will be passed to the shader.
  156. * @param engine Engine to be used to render the effect
  157. * @param defines Define statements to be added to the shader.
  158. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  159. * @param onCompiled Callback that will be called when the shader is compiled.
  160. * @param onError Callback that will be called if an error occurs during shader compilation.
  161. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  162. */
  163. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  164. if (samplers === void 0) { samplers = null; }
  165. if (defines === void 0) { defines = null; }
  166. if (fallbacks === void 0) { fallbacks = null; }
  167. if (onCompiled === void 0) { onCompiled = null; }
  168. if (onError === void 0) { onError = null; }
  169. var _this = this;
  170. /**
  171. * Unique ID of the effect.
  172. */
  173. this.uniqueId = 0;
  174. /**
  175. * Observable that will be called when the shader is compiled.
  176. */
  177. this.onCompileObservable = new BABYLON.Observable();
  178. /**
  179. * Observable that will be called if an error occurs during shader compilation.
  180. */
  181. this.onErrorObservable = new BABYLON.Observable();
  182. /**
  183. * Observable that will be called when effect is bound.
  184. */
  185. this.onBindObservable = new BABYLON.Observable();
  186. this._uniformBuffersNames = {};
  187. this._isReady = false;
  188. this._compilationError = "";
  189. this.name = baseName;
  190. if (attributesNamesOrOptions.attributes) {
  191. var options = attributesNamesOrOptions;
  192. this._engine = uniformsNamesOrEngine;
  193. this._attributesNames = options.attributes;
  194. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  195. this._samplers = options.samplers;
  196. this.defines = options.defines;
  197. this.onError = options.onError;
  198. this.onCompiled = options.onCompiled;
  199. this._fallbacks = options.fallbacks;
  200. this._indexParameters = options.indexParameters;
  201. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  202. if (options.uniformBuffersNames) {
  203. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  204. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  205. }
  206. }
  207. }
  208. else {
  209. this._engine = engine;
  210. this.defines = defines;
  211. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  212. this._samplers = samplers;
  213. this._attributesNames = attributesNamesOrOptions;
  214. this.onError = onError;
  215. this.onCompiled = onCompiled;
  216. this._indexParameters = indexParameters;
  217. this._fallbacks = fallbacks;
  218. }
  219. this.uniqueId = Effect._uniqueIdSeed++;
  220. if (this._getFromCache(baseName)) {
  221. this._prepareEffect();
  222. return;
  223. }
  224. var vertexSource;
  225. var fragmentSource;
  226. if (baseName.vertexElement) {
  227. vertexSource = document.getElementById(baseName.vertexElement);
  228. if (!vertexSource) {
  229. vertexSource = baseName.vertexElement;
  230. }
  231. }
  232. else {
  233. vertexSource = baseName.vertex || baseName;
  234. }
  235. if (baseName.fragmentElement) {
  236. fragmentSource = document.getElementById(baseName.fragmentElement);
  237. if (!fragmentSource) {
  238. fragmentSource = baseName.fragmentElement;
  239. }
  240. }
  241. else {
  242. fragmentSource = baseName.fragment || baseName;
  243. }
  244. var finalVertexCode;
  245. this._loadVertexShaderAsync(vertexSource)
  246. .then(function (vertexCode) {
  247. return _this._processIncludesAsync(vertexCode);
  248. })
  249. .then(function (vertexCodeWithIncludes) {
  250. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  251. return _this._loadFragmentShaderAsync(fragmentSource);
  252. })
  253. .then(function (fragmentCode) {
  254. return _this._processIncludesAsync(fragmentCode);
  255. })
  256. .then(function (fragmentCodeWithIncludes) {
  257. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  258. if (baseName) {
  259. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  260. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  261. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  262. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  263. }
  264. else {
  265. _this._vertexSourceCode = finalVertexCode;
  266. _this._fragmentSourceCode = migratedFragmentCode;
  267. }
  268. _this._setInCache(baseName);
  269. _this._prepareEffect();
  270. });
  271. }
  272. Effect.prototype._getSourceCacheKey = function (baseName) {
  273. var cacheKey = baseName;
  274. if (this._indexParameters) {
  275. for (var key in this._indexParameters) {
  276. if (this._indexParameters.hasOwnProperty(key)) {
  277. cacheKey += "|";
  278. cacheKey += key;
  279. cacheKey += "_";
  280. cacheKey += this._indexParameters[key];
  281. }
  282. }
  283. }
  284. return cacheKey;
  285. };
  286. Effect.prototype._getFromCache = function (baseName) {
  287. if (typeof baseName !== "string") {
  288. return false;
  289. }
  290. var cacheKey = this._getSourceCacheKey(baseName);
  291. var sources = Effect._sourceCache[cacheKey];
  292. if (!sources) {
  293. return false;
  294. }
  295. this._vertexSourceCode = sources.vertex;
  296. this._fragmentSourceCode = sources.fragment;
  297. return true;
  298. };
  299. Effect.prototype._setInCache = function (baseName) {
  300. if (typeof baseName !== "string") {
  301. return;
  302. }
  303. var cacheKey = this._getSourceCacheKey(baseName);
  304. Effect._sourceCache[cacheKey] = {
  305. vertex: this._vertexSourceCode,
  306. fragment: this._fragmentSourceCode
  307. };
  308. };
  309. Object.defineProperty(Effect.prototype, "key", {
  310. /**
  311. * Unique key for this effect
  312. */
  313. get: function () {
  314. return this._key;
  315. },
  316. enumerable: true,
  317. configurable: true
  318. });
  319. /**
  320. * If the effect has been compiled and prepared.
  321. * @returns if the effect is compiled and prepared.
  322. */
  323. Effect.prototype.isReady = function () {
  324. return this._isReady;
  325. };
  326. /**
  327. * The engine the effect was initialized with.
  328. * @returns the engine.
  329. */
  330. Effect.prototype.getEngine = function () {
  331. return this._engine;
  332. };
  333. /**
  334. * The compiled webGL program for the effect
  335. * @returns the webGL program.
  336. */
  337. Effect.prototype.getProgram = function () {
  338. return this._program;
  339. };
  340. /**
  341. * The set of names of attribute variables for the shader.
  342. * @returns An array of attribute names.
  343. */
  344. Effect.prototype.getAttributesNames = function () {
  345. return this._attributesNames;
  346. };
  347. /**
  348. * Returns the attribute at the given index.
  349. * @param index The index of the attribute.
  350. * @returns The location of the attribute.
  351. */
  352. Effect.prototype.getAttributeLocation = function (index) {
  353. return this._attributes[index];
  354. };
  355. /**
  356. * Returns the attribute based on the name of the variable.
  357. * @param name of the attribute to look up.
  358. * @returns the attribute location.
  359. */
  360. Effect.prototype.getAttributeLocationByName = function (name) {
  361. var index = this._attributesNames.indexOf(name);
  362. return this._attributes[index];
  363. };
  364. /**
  365. * The number of attributes.
  366. * @returns the numnber of attributes.
  367. */
  368. Effect.prototype.getAttributesCount = function () {
  369. return this._attributes.length;
  370. };
  371. /**
  372. * Gets the index of a uniform variable.
  373. * @param uniformName of the uniform to look up.
  374. * @returns the index.
  375. */
  376. Effect.prototype.getUniformIndex = function (uniformName) {
  377. return this._uniformsNames.indexOf(uniformName);
  378. };
  379. /**
  380. * Returns the attribute based on the name of the variable.
  381. * @param uniformName of the uniform to look up.
  382. * @returns the location of the uniform.
  383. */
  384. Effect.prototype.getUniform = function (uniformName) {
  385. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  386. };
  387. /**
  388. * Returns an array of sampler variable names
  389. * @returns The array of sampler variable neames.
  390. */
  391. Effect.prototype.getSamplers = function () {
  392. return this._samplers;
  393. };
  394. /**
  395. * The error from the last compilation.
  396. * @returns the error string.
  397. */
  398. Effect.prototype.getCompilationError = function () {
  399. return this._compilationError;
  400. };
  401. /**
  402. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  403. * @param func The callback to be used.
  404. */
  405. Effect.prototype.executeWhenCompiled = function (func) {
  406. if (this.isReady()) {
  407. func(this);
  408. return;
  409. }
  410. this.onCompileObservable.add(function (effect) {
  411. func(effect);
  412. });
  413. };
  414. /** @ignore */
  415. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  416. if (BABYLON.Tools.IsWindowObjectExist()) {
  417. // DOM element ?
  418. if (vertex instanceof HTMLElement) {
  419. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  420. return Promise.resolve(vertexCode);
  421. }
  422. }
  423. // Base64 encoded ?
  424. if (vertex.substr(0, 7) === "base64:") {
  425. var vertexBinary = window.atob(vertex.substr(7));
  426. return Promise.resolve(vertexBinary);
  427. }
  428. // Is in local store ?
  429. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  430. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  431. }
  432. var vertexShaderUrl;
  433. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  434. vertexShaderUrl = vertex;
  435. }
  436. else {
  437. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  438. }
  439. // Vertex shader
  440. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  441. };
  442. /** @ignore */
  443. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  444. if (BABYLON.Tools.IsWindowObjectExist()) {
  445. // DOM element ?
  446. if (fragment instanceof HTMLElement) {
  447. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  448. return Promise.resolve(fragmentCode);
  449. }
  450. }
  451. // Base64 encoded ?
  452. if (fragment.substr(0, 7) === "base64:") {
  453. var fragmentBinary = window.atob(fragment.substr(7));
  454. return Promise.resolve(fragmentBinary);
  455. }
  456. // Is in local store ?
  457. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  458. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  459. }
  460. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  461. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  462. }
  463. var fragmentShaderUrl;
  464. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  465. fragmentShaderUrl = fragment;
  466. }
  467. else {
  468. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  469. }
  470. // Fragment shader
  471. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  472. };
  473. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  474. // Rebuild shaders source code
  475. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  476. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  477. vertexCode = prefix + vertexCode;
  478. fragmentCode = prefix + fragmentCode;
  479. // Number lines of shaders source code
  480. var i = 2;
  481. var regex = /\n/gm;
  482. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  483. i = 2;
  484. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  485. // Dump shaders name and formatted source code
  486. if (this.name.vertexElement) {
  487. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  488. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  489. }
  490. else if (this.name.vertex) {
  491. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  492. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  493. }
  494. else {
  495. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  496. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  497. }
  498. };
  499. ;
  500. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  501. var preparedSourceCode = this._processPrecision(sourceCode);
  502. if (this._engine.webGLVersion == 1) {
  503. return preparedSourceCode;
  504. }
  505. // Already converted
  506. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  507. return preparedSourceCode.replace("#version 300 es", "");
  508. }
  509. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  510. // Remove extensions
  511. // #extension GL_OES_standard_derivatives : enable
  512. // #extension GL_EXT_shader_texture_lod : enable
  513. // #extension GL_EXT_frag_depth : enable
  514. // #extension GL_EXT_draw_buffers : require
  515. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  516. var result = preparedSourceCode.replace(regex, "");
  517. // Migrate to GLSL v300
  518. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  519. result = result.replace(/attribute[ \t]/g, "in ");
  520. result = result.replace(/[ \t]attribute/g, " in");
  521. if (isFragment) {
  522. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  523. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  524. result = result.replace(/texture2D\s*\(/g, "texture(");
  525. result = result.replace(/textureCube\s*\(/g, "texture(");
  526. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  527. result = result.replace(/gl_FragColor/g, "glFragColor");
  528. result = result.replace(/gl_FragData/g, "glFragData");
  529. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  530. }
  531. return result;
  532. };
  533. Effect.prototype._processIncludesAsync = function (sourceCode) {
  534. var _this = this;
  535. return new Promise(function (resolve, reject) {
  536. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  537. var match = regex.exec(sourceCode);
  538. var returnValue = sourceCode;
  539. while (match != null) {
  540. var includeFile = match[1];
  541. // Uniform declaration
  542. if (includeFile.indexOf("__decl__") !== -1) {
  543. includeFile = includeFile.replace(/__decl__/, "");
  544. if (_this._engine.supportsUniformBuffers) {
  545. includeFile = includeFile.replace(/Vertex/, "Ubo");
  546. includeFile = includeFile.replace(/Fragment/, "Ubo");
  547. }
  548. includeFile = includeFile + "Declaration";
  549. }
  550. if (Effect.IncludesShadersStore[includeFile]) {
  551. // Substitution
  552. var includeContent = Effect.IncludesShadersStore[includeFile];
  553. if (match[2]) {
  554. var splits = match[3].split(",");
  555. for (var index = 0; index < splits.length; index += 2) {
  556. var source = new RegExp(splits[index], "g");
  557. var dest = splits[index + 1];
  558. includeContent = includeContent.replace(source, dest);
  559. }
  560. }
  561. if (match[4]) {
  562. var indexString = match[5];
  563. if (indexString.indexOf("..") !== -1) {
  564. var indexSplits = indexString.split("..");
  565. var minIndex = parseInt(indexSplits[0]);
  566. var maxIndex = parseInt(indexSplits[1]);
  567. var sourceIncludeContent = includeContent.slice(0);
  568. includeContent = "";
  569. if (isNaN(maxIndex)) {
  570. maxIndex = _this._indexParameters[indexSplits[1]];
  571. }
  572. for (var i = minIndex; i < maxIndex; i++) {
  573. if (!_this._engine.supportsUniformBuffers) {
  574. // Ubo replacement
  575. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  576. return p1 + "{X}";
  577. });
  578. }
  579. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  580. }
  581. }
  582. else {
  583. if (!_this._engine.supportsUniformBuffers) {
  584. // Ubo replacement
  585. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  586. return p1 + "{X}";
  587. });
  588. }
  589. includeContent = includeContent.replace(/\{X\}/g, indexString);
  590. }
  591. }
  592. // Replace
  593. returnValue = returnValue.replace(match[0], includeContent);
  594. }
  595. else {
  596. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  597. _this._engine._loadFileAsync(includeShaderUrl)
  598. .then(function (fileContent) {
  599. Effect.IncludesShadersStore[includeFile] = fileContent;
  600. return _this._processIncludesAsync(returnValue);
  601. })
  602. .then(function (returnValue) {
  603. resolve(returnValue);
  604. });
  605. return;
  606. }
  607. match = regex.exec(sourceCode);
  608. }
  609. resolve(returnValue);
  610. });
  611. };
  612. Effect.prototype._processPrecision = function (source) {
  613. if (source.indexOf("precision highp float") === -1) {
  614. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  615. source = "precision mediump float;\n" + source;
  616. }
  617. else {
  618. source = "precision highp float;\n" + source;
  619. }
  620. }
  621. else {
  622. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  623. source = source.replace("precision highp float", "precision mediump float");
  624. }
  625. }
  626. return source;
  627. };
  628. /**
  629. * Recompiles the webGL program
  630. * @param vertexSourceCode The source code for the vertex shader.
  631. * @param fragmentSourceCode The source code for the fragment shader.
  632. * @param onCompiled Callback called when completed.
  633. * @param onError Callback called on error.
  634. */
  635. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  636. var _this = this;
  637. this._isReady = false;
  638. this._vertexSourceCodeOverride = vertexSourceCode;
  639. this._fragmentSourceCodeOverride = fragmentSourceCode;
  640. this.onError = function (effect, error) {
  641. if (onError) {
  642. onError(error);
  643. }
  644. };
  645. this.onCompiled = function () {
  646. var scenes = _this.getEngine().scenes;
  647. for (var i = 0; i < scenes.length; i++) {
  648. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  649. }
  650. if (onCompiled) {
  651. onCompiled(_this._program);
  652. }
  653. };
  654. this._fallbacks = null;
  655. this._prepareEffect();
  656. };
  657. /**
  658. * Gets the uniform locations of the the specified variable names
  659. * @param names THe names of the variables to lookup.
  660. * @returns Array of locations in the same order as variable names.
  661. */
  662. Effect.prototype.getSpecificUniformLocations = function (names) {
  663. var engine = this._engine;
  664. return engine.getUniforms(this._program, names);
  665. };
  666. /**
  667. * Prepares the effect
  668. */
  669. Effect.prototype._prepareEffect = function () {
  670. var attributesNames = this._attributesNames;
  671. var defines = this.defines;
  672. var fallbacks = this._fallbacks;
  673. this._valueCache = {};
  674. var previousProgram = this._program;
  675. try {
  676. var engine = this._engine;
  677. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  678. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  679. }
  680. else {
  681. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  682. }
  683. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  684. if (engine.supportsUniformBuffers) {
  685. for (var name in this._uniformBuffersNames) {
  686. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  687. }
  688. }
  689. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  690. this._attributes = engine.getAttributes(this._program, attributesNames);
  691. var index;
  692. for (index = 0; index < this._samplers.length; index++) {
  693. var sampler = this.getUniform(this._samplers[index]);
  694. if (sampler == null) {
  695. this._samplers.splice(index, 1);
  696. index--;
  697. }
  698. }
  699. engine.bindSamplers(this);
  700. this._compilationError = "";
  701. this._isReady = true;
  702. if (this.onCompiled) {
  703. this.onCompiled(this);
  704. }
  705. this.onCompileObservable.notifyObservers(this);
  706. this.onCompileObservable.clear();
  707. // Unbind mesh reference in fallbacks
  708. if (this._fallbacks) {
  709. this._fallbacks.unBindMesh();
  710. }
  711. if (previousProgram) {
  712. this.getEngine()._deleteProgram(previousProgram);
  713. }
  714. }
  715. catch (e) {
  716. this._compilationError = e.message;
  717. // Let's go through fallbacks then
  718. BABYLON.Tools.Error("Unable to compile effect:");
  719. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  720. return " " + uniform;
  721. }));
  722. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  723. return " " + attribute;
  724. }));
  725. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  726. BABYLON.Tools.Error("Error: " + this._compilationError);
  727. if (previousProgram) {
  728. this._program = previousProgram;
  729. this._isReady = true;
  730. if (this.onError) {
  731. this.onError(this, this._compilationError);
  732. }
  733. this.onErrorObservable.notifyObservers(this);
  734. }
  735. if (fallbacks && fallbacks.isMoreFallbacks) {
  736. BABYLON.Tools.Error("Trying next fallback.");
  737. this.defines = fallbacks.reduce(this.defines, this);
  738. this._prepareEffect();
  739. }
  740. else {
  741. if (this.onError) {
  742. this.onError(this, this._compilationError);
  743. }
  744. this.onErrorObservable.notifyObservers(this);
  745. this.onErrorObservable.clear();
  746. // Unbind mesh reference in fallbacks
  747. if (this._fallbacks) {
  748. this._fallbacks.unBindMesh();
  749. }
  750. }
  751. }
  752. };
  753. Object.defineProperty(Effect.prototype, "isSupported", {
  754. /**
  755. * Checks if the effect is supported. (Must be called after compilation)
  756. */
  757. get: function () {
  758. return this._compilationError === "";
  759. },
  760. enumerable: true,
  761. configurable: true
  762. });
  763. /**
  764. * Binds a texture to the engine to be used as output of the shader.
  765. * @param channel Name of the output variable.
  766. * @param texture Texture to bind.
  767. */
  768. Effect.prototype._bindTexture = function (channel, texture) {
  769. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  770. };
  771. /**
  772. * Sets a texture on the engine to be used in the shader.
  773. * @param channel Name of the sampler variable.
  774. * @param texture Texture to set.
  775. */
  776. Effect.prototype.setTexture = function (channel, texture) {
  777. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  778. };
  779. /**
  780. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  781. * @param channel Name of the sampler variable.
  782. * @param texture Texture to set.
  783. */
  784. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  785. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  786. };
  787. /**
  788. * Sets an array of textures on the engine to be used in the shader.
  789. * @param channel Name of the variable.
  790. * @param textures Textures to set.
  791. */
  792. Effect.prototype.setTextureArray = function (channel, textures) {
  793. if (this._samplers.indexOf(channel + "Ex") === -1) {
  794. var initialPos = this._samplers.indexOf(channel);
  795. for (var index = 1; index < textures.length; index++) {
  796. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  797. }
  798. }
  799. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  800. };
  801. /**
  802. * 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)
  803. * @param channel Name of the sampler variable.
  804. * @param postProcess Post process to get the input texture from.
  805. */
  806. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  807. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  808. };
  809. /** @ignore */
  810. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  811. var cache = this._valueCache[uniformName];
  812. var flag = matrix.updateFlag;
  813. if (cache !== undefined && cache === flag) {
  814. return false;
  815. }
  816. this._valueCache[uniformName] = flag;
  817. return true;
  818. };
  819. /** @ignore */
  820. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  821. var cache = this._valueCache[uniformName];
  822. if (!cache) {
  823. cache = [x, y];
  824. this._valueCache[uniformName] = cache;
  825. return true;
  826. }
  827. var changed = false;
  828. if (cache[0] !== x) {
  829. cache[0] = x;
  830. changed = true;
  831. }
  832. if (cache[1] !== y) {
  833. cache[1] = y;
  834. changed = true;
  835. }
  836. return changed;
  837. };
  838. /** @ignore */
  839. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  840. var cache = this._valueCache[uniformName];
  841. if (!cache) {
  842. cache = [x, y, z];
  843. this._valueCache[uniformName] = cache;
  844. return true;
  845. }
  846. var changed = false;
  847. if (cache[0] !== x) {
  848. cache[0] = x;
  849. changed = true;
  850. }
  851. if (cache[1] !== y) {
  852. cache[1] = y;
  853. changed = true;
  854. }
  855. if (cache[2] !== z) {
  856. cache[2] = z;
  857. changed = true;
  858. }
  859. return changed;
  860. };
  861. /** @ignore */
  862. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  863. var cache = this._valueCache[uniformName];
  864. if (!cache) {
  865. cache = [x, y, z, w];
  866. this._valueCache[uniformName] = cache;
  867. return true;
  868. }
  869. var changed = false;
  870. if (cache[0] !== x) {
  871. cache[0] = x;
  872. changed = true;
  873. }
  874. if (cache[1] !== y) {
  875. cache[1] = y;
  876. changed = true;
  877. }
  878. if (cache[2] !== z) {
  879. cache[2] = z;
  880. changed = true;
  881. }
  882. if (cache[3] !== w) {
  883. cache[3] = w;
  884. changed = true;
  885. }
  886. return changed;
  887. };
  888. /**
  889. * Binds a buffer to a uniform.
  890. * @param buffer Buffer to bind.
  891. * @param name Name of the uniform variable to bind to.
  892. */
  893. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  894. var bufferName = this._uniformBuffersNames[name];
  895. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  896. return;
  897. }
  898. Effect._baseCache[bufferName] = buffer;
  899. this._engine.bindUniformBufferBase(buffer, bufferName);
  900. };
  901. /**
  902. * Binds block to a uniform.
  903. * @param blockName Name of the block to bind.
  904. * @param index Index to bind.
  905. */
  906. Effect.prototype.bindUniformBlock = function (blockName, index) {
  907. this._engine.bindUniformBlock(this._program, blockName, index);
  908. };
  909. /**
  910. * Sets an interger value on a uniform variable.
  911. * @param uniformName Name of the variable.
  912. * @param value Value to be set.
  913. * @returns this effect.
  914. */
  915. Effect.prototype.setInt = function (uniformName, value) {
  916. var cache = this._valueCache[uniformName];
  917. if (cache !== undefined && cache === value)
  918. return this;
  919. this._valueCache[uniformName] = value;
  920. this._engine.setInt(this.getUniform(uniformName), value);
  921. return this;
  922. };
  923. /**
  924. * Sets an int array on a uniform variable.
  925. * @param uniformName Name of the variable.
  926. * @param array array to be set.
  927. * @returns this effect.
  928. */
  929. Effect.prototype.setIntArray = function (uniformName, array) {
  930. this._valueCache[uniformName] = null;
  931. this._engine.setIntArray(this.getUniform(uniformName), array);
  932. return this;
  933. };
  934. /**
  935. * 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)
  936. * @param uniformName Name of the variable.
  937. * @param array array to be set.
  938. * @returns this effect.
  939. */
  940. Effect.prototype.setIntArray2 = function (uniformName, array) {
  941. this._valueCache[uniformName] = null;
  942. this._engine.setIntArray2(this.getUniform(uniformName), array);
  943. return this;
  944. };
  945. /**
  946. * 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)
  947. * @param uniformName Name of the variable.
  948. * @param array array to be set.
  949. * @returns this effect.
  950. */
  951. Effect.prototype.setIntArray3 = function (uniformName, array) {
  952. this._valueCache[uniformName] = null;
  953. this._engine.setIntArray3(this.getUniform(uniformName), array);
  954. return this;
  955. };
  956. /**
  957. * 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)
  958. * @param uniformName Name of the variable.
  959. * @param array array to be set.
  960. * @returns this effect.
  961. */
  962. Effect.prototype.setIntArray4 = function (uniformName, array) {
  963. this._valueCache[uniformName] = null;
  964. this._engine.setIntArray4(this.getUniform(uniformName), array);
  965. return this;
  966. };
  967. /**
  968. * Sets an float array on a uniform variable.
  969. * @param uniformName Name of the variable.
  970. * @param array array to be set.
  971. * @returns this effect.
  972. */
  973. Effect.prototype.setFloatArray = function (uniformName, array) {
  974. this._valueCache[uniformName] = null;
  975. this._engine.setFloatArray(this.getUniform(uniformName), array);
  976. return this;
  977. };
  978. /**
  979. * 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)
  980. * @param uniformName Name of the variable.
  981. * @param array array to be set.
  982. * @returns this effect.
  983. */
  984. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  985. this._valueCache[uniformName] = null;
  986. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  987. return this;
  988. };
  989. /**
  990. * 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)
  991. * @param uniformName Name of the variable.
  992. * @param array array to be set.
  993. * @returns this effect.
  994. */
  995. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  996. this._valueCache[uniformName] = null;
  997. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  998. return this;
  999. };
  1000. /**
  1001. * 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)
  1002. * @param uniformName Name of the variable.
  1003. * @param array array to be set.
  1004. * @returns this effect.
  1005. */
  1006. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  1007. this._valueCache[uniformName] = null;
  1008. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  1009. return this;
  1010. };
  1011. /**
  1012. * Sets an array on a uniform variable.
  1013. * @param uniformName Name of the variable.
  1014. * @param array array to be set.
  1015. * @returns this effect.
  1016. */
  1017. Effect.prototype.setArray = function (uniformName, array) {
  1018. this._valueCache[uniformName] = null;
  1019. this._engine.setArray(this.getUniform(uniformName), array);
  1020. return this;
  1021. };
  1022. /**
  1023. * 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)
  1024. * @param uniformName Name of the variable.
  1025. * @param array array to be set.
  1026. * @returns this effect.
  1027. */
  1028. Effect.prototype.setArray2 = function (uniformName, array) {
  1029. this._valueCache[uniformName] = null;
  1030. this._engine.setArray2(this.getUniform(uniformName), array);
  1031. return this;
  1032. };
  1033. /**
  1034. * 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)
  1035. * @param uniformName Name of the variable.
  1036. * @param array array to be set.
  1037. * @returns this effect.
  1038. */
  1039. Effect.prototype.setArray3 = function (uniformName, array) {
  1040. this._valueCache[uniformName] = null;
  1041. this._engine.setArray3(this.getUniform(uniformName), array);
  1042. return this;
  1043. };
  1044. /**
  1045. * 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)
  1046. * @param uniformName Name of the variable.
  1047. * @param array array to be set.
  1048. * @returns this effect.
  1049. */
  1050. Effect.prototype.setArray4 = function (uniformName, array) {
  1051. this._valueCache[uniformName] = null;
  1052. this._engine.setArray4(this.getUniform(uniformName), array);
  1053. return this;
  1054. };
  1055. /**
  1056. * Sets matrices on a uniform variable.
  1057. * @param uniformName Name of the variable.
  1058. * @param matrices matrices to be set.
  1059. * @returns this effect.
  1060. */
  1061. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1062. if (!matrices) {
  1063. return this;
  1064. }
  1065. this._valueCache[uniformName] = null;
  1066. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1067. return this;
  1068. };
  1069. /**
  1070. * Sets matrix on a uniform variable.
  1071. * @param uniformName Name of the variable.
  1072. * @param matrix matrix to be set.
  1073. * @returns this effect.
  1074. */
  1075. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1076. if (this._cacheMatrix(uniformName, matrix)) {
  1077. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1078. }
  1079. return this;
  1080. };
  1081. /**
  1082. * 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)
  1083. * @param uniformName Name of the variable.
  1084. * @param matrix matrix to be set.
  1085. * @returns this effect.
  1086. */
  1087. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1088. this._valueCache[uniformName] = null;
  1089. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1090. return this;
  1091. };
  1092. /**
  1093. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1094. * @param uniformName Name of the variable.
  1095. * @param matrix matrix to be set.
  1096. * @returns this effect.
  1097. */
  1098. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1099. this._valueCache[uniformName] = null;
  1100. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1101. return this;
  1102. };
  1103. /**
  1104. * Sets a float on a uniform variable.
  1105. * @param uniformName Name of the variable.
  1106. * @param value value to be set.
  1107. * @returns this effect.
  1108. */
  1109. Effect.prototype.setFloat = function (uniformName, value) {
  1110. var cache = this._valueCache[uniformName];
  1111. if (cache !== undefined && cache === value)
  1112. return this;
  1113. this._valueCache[uniformName] = value;
  1114. this._engine.setFloat(this.getUniform(uniformName), value);
  1115. return this;
  1116. };
  1117. /**
  1118. * Sets a boolean on a uniform variable.
  1119. * @param uniformName Name of the variable.
  1120. * @param bool value to be set.
  1121. * @returns this effect.
  1122. */
  1123. Effect.prototype.setBool = function (uniformName, bool) {
  1124. var cache = this._valueCache[uniformName];
  1125. if (cache !== undefined && cache === bool)
  1126. return this;
  1127. this._valueCache[uniformName] = bool;
  1128. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1129. return this;
  1130. };
  1131. /**
  1132. * Sets a Vector2 on a uniform variable.
  1133. * @param uniformName Name of the variable.
  1134. * @param vector2 vector2 to be set.
  1135. * @returns this effect.
  1136. */
  1137. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1138. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1139. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1140. }
  1141. return this;
  1142. };
  1143. /**
  1144. * Sets a float2 on a uniform variable.
  1145. * @param uniformName Name of the variable.
  1146. * @param x First float in float2.
  1147. * @param y Second float in float2.
  1148. * @returns this effect.
  1149. */
  1150. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1151. if (this._cacheFloat2(uniformName, x, y)) {
  1152. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1153. }
  1154. return this;
  1155. };
  1156. /**
  1157. * Sets a Vector3 on a uniform variable.
  1158. * @param uniformName Name of the variable.
  1159. * @param vector3 Value to be set.
  1160. * @returns this effect.
  1161. */
  1162. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1163. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1164. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1165. }
  1166. return this;
  1167. };
  1168. /**
  1169. * Sets a float3 on a uniform variable.
  1170. * @param uniformName Name of the variable.
  1171. * @param x First float in float3.
  1172. * @param y Second float in float3.
  1173. * @param z Third float in float3.
  1174. * @returns this effect.
  1175. */
  1176. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1177. if (this._cacheFloat3(uniformName, x, y, z)) {
  1178. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1179. }
  1180. return this;
  1181. };
  1182. /**
  1183. * Sets a Vector4 on a uniform variable.
  1184. * @param uniformName Name of the variable.
  1185. * @param vector4 Value to be set.
  1186. * @returns this effect.
  1187. */
  1188. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1189. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1190. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1191. }
  1192. return this;
  1193. };
  1194. /**
  1195. * Sets a float4 on a uniform variable.
  1196. * @param uniformName Name of the variable.
  1197. * @param x First float in float4.
  1198. * @param y Second float in float4.
  1199. * @param z Third float in float4.
  1200. * @param w Fourth float in float4.
  1201. * @returns this effect.
  1202. */
  1203. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1204. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1205. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1206. }
  1207. return this;
  1208. };
  1209. /**
  1210. * Sets a Color3 on a uniform variable.
  1211. * @param uniformName Name of the variable.
  1212. * @param color3 Value to be set.
  1213. * @returns this effect.
  1214. */
  1215. Effect.prototype.setColor3 = function (uniformName, color3) {
  1216. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1217. this._engine.setColor3(this.getUniform(uniformName), color3);
  1218. }
  1219. return this;
  1220. };
  1221. /**
  1222. * Sets a Color4 on a uniform variable.
  1223. * @param uniformName Name of the variable.
  1224. * @param color3 Value to be set.
  1225. * @param alpha Alpha value to be set.
  1226. * @returns this effect.
  1227. */
  1228. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1229. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1230. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1231. }
  1232. return this;
  1233. };
  1234. /**
  1235. * Sets a Color4 on a uniform variable
  1236. * @param uniformName defines the name of the variable
  1237. * @param color4 defines the value to be set
  1238. * @returns this effect.
  1239. */
  1240. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1241. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1242. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1243. }
  1244. return this;
  1245. };
  1246. /**
  1247. * Resets the cache of effects.
  1248. */
  1249. Effect.ResetCache = function () {
  1250. Effect._baseCache = {};
  1251. };
  1252. Effect._uniqueIdSeed = 0;
  1253. Effect._baseCache = {};
  1254. Effect._sourceCache = {};
  1255. // Statics
  1256. /**
  1257. * Store of each shader (The can be looked up using effect.key)
  1258. */
  1259. Effect.ShadersStore = {};
  1260. /**
  1261. * Store of each included file for a shader (The can be looked up using effect.key)
  1262. */
  1263. Effect.IncludesShadersStore = {};
  1264. return Effect;
  1265. }());
  1266. BABYLON.Effect = Effect;
  1267. })(BABYLON || (BABYLON = {}));
  1268. //# sourceMappingURL=babylon.effect.js.map
  1269. //# sourceMappingURL=babylon.types.js.map
  1270. var BABYLON;
  1271. (function (BABYLON) {
  1272. var KeyboardEventTypes = /** @class */ (function () {
  1273. function KeyboardEventTypes() {
  1274. }
  1275. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1276. get: function () {
  1277. return KeyboardEventTypes._KEYDOWN;
  1278. },
  1279. enumerable: true,
  1280. configurable: true
  1281. });
  1282. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1283. get: function () {
  1284. return KeyboardEventTypes._KEYUP;
  1285. },
  1286. enumerable: true,
  1287. configurable: true
  1288. });
  1289. KeyboardEventTypes._KEYDOWN = 0x01;
  1290. KeyboardEventTypes._KEYUP = 0x02;
  1291. return KeyboardEventTypes;
  1292. }());
  1293. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1294. var KeyboardInfo = /** @class */ (function () {
  1295. function KeyboardInfo(type, event) {
  1296. this.type = type;
  1297. this.event = event;
  1298. }
  1299. return KeyboardInfo;
  1300. }());
  1301. BABYLON.KeyboardInfo = KeyboardInfo;
  1302. /**
  1303. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1304. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1305. */
  1306. var KeyboardInfoPre = /** @class */ (function (_super) {
  1307. __extends(KeyboardInfoPre, _super);
  1308. function KeyboardInfoPre(type, event) {
  1309. var _this = _super.call(this, type, event) || this;
  1310. _this.skipOnPointerObservable = false;
  1311. return _this;
  1312. }
  1313. return KeyboardInfoPre;
  1314. }(KeyboardInfo));
  1315. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1316. })(BABYLON || (BABYLON = {}));
  1317. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1318. var BABYLON;
  1319. (function (BABYLON) {
  1320. var PointerEventTypes = /** @class */ (function () {
  1321. function PointerEventTypes() {
  1322. }
  1323. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1324. get: function () {
  1325. return PointerEventTypes._POINTERDOWN;
  1326. },
  1327. enumerable: true,
  1328. configurable: true
  1329. });
  1330. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1331. get: function () {
  1332. return PointerEventTypes._POINTERUP;
  1333. },
  1334. enumerable: true,
  1335. configurable: true
  1336. });
  1337. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1338. get: function () {
  1339. return PointerEventTypes._POINTERMOVE;
  1340. },
  1341. enumerable: true,
  1342. configurable: true
  1343. });
  1344. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1345. get: function () {
  1346. return PointerEventTypes._POINTERWHEEL;
  1347. },
  1348. enumerable: true,
  1349. configurable: true
  1350. });
  1351. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1352. get: function () {
  1353. return PointerEventTypes._POINTERPICK;
  1354. },
  1355. enumerable: true,
  1356. configurable: true
  1357. });
  1358. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1359. get: function () {
  1360. return PointerEventTypes._POINTERTAP;
  1361. },
  1362. enumerable: true,
  1363. configurable: true
  1364. });
  1365. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1366. get: function () {
  1367. return PointerEventTypes._POINTERDOUBLETAP;
  1368. },
  1369. enumerable: true,
  1370. configurable: true
  1371. });
  1372. PointerEventTypes._POINTERDOWN = 0x01;
  1373. PointerEventTypes._POINTERUP = 0x02;
  1374. PointerEventTypes._POINTERMOVE = 0x04;
  1375. PointerEventTypes._POINTERWHEEL = 0x08;
  1376. PointerEventTypes._POINTERPICK = 0x10;
  1377. PointerEventTypes._POINTERTAP = 0x20;
  1378. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1379. return PointerEventTypes;
  1380. }());
  1381. BABYLON.PointerEventTypes = PointerEventTypes;
  1382. var PointerInfoBase = /** @class */ (function () {
  1383. function PointerInfoBase(type, event) {
  1384. this.type = type;
  1385. this.event = event;
  1386. }
  1387. return PointerInfoBase;
  1388. }());
  1389. BABYLON.PointerInfoBase = PointerInfoBase;
  1390. /**
  1391. * This class is used to store pointer related info for the onPrePointerObservable event.
  1392. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1393. */
  1394. var PointerInfoPre = /** @class */ (function (_super) {
  1395. __extends(PointerInfoPre, _super);
  1396. function PointerInfoPre(type, event, localX, localY) {
  1397. var _this = _super.call(this, type, event) || this;
  1398. _this.skipOnPointerObservable = false;
  1399. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1400. return _this;
  1401. }
  1402. return PointerInfoPre;
  1403. }(PointerInfoBase));
  1404. BABYLON.PointerInfoPre = PointerInfoPre;
  1405. /**
  1406. * This type contains all the data related to a pointer event in Babylon.js.
  1407. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1408. */
  1409. var PointerInfo = /** @class */ (function (_super) {
  1410. __extends(PointerInfo, _super);
  1411. function PointerInfo(type, event, pickInfo) {
  1412. var _this = _super.call(this, type, event) || this;
  1413. _this.pickInfo = pickInfo;
  1414. return _this;
  1415. }
  1416. return PointerInfo;
  1417. }(PointerInfoBase));
  1418. BABYLON.PointerInfo = PointerInfo;
  1419. })(BABYLON || (BABYLON = {}));
  1420. //# sourceMappingURL=babylon.pointerEvents.js.map
  1421. var BABYLON;
  1422. (function (BABYLON) {
  1423. BABYLON.ToGammaSpace = 1 / 2.2;
  1424. BABYLON.ToLinearSpace = 2.2;
  1425. BABYLON.Epsilon = 0.001;
  1426. /**
  1427. * Class used to hold a RBG color
  1428. */
  1429. var Color3 = /** @class */ (function () {
  1430. /**
  1431. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1432. * @param r defines the red component (between 0 and 1, default is 0)
  1433. * @param g defines the green component (between 0 and 1, default is 0)
  1434. * @param b defines the blue component (between 0 and 1, default is 0)
  1435. */
  1436. function Color3(
  1437. /**
  1438. * Defines the red component (between 0 and 1, default is 0)
  1439. */
  1440. r,
  1441. /**
  1442. * Defines the green component (between 0 and 1, default is 0)
  1443. */
  1444. g,
  1445. /**
  1446. * Defines the blue component (between 0 and 1, default is 0)
  1447. */
  1448. b) {
  1449. if (r === void 0) { r = 0; }
  1450. if (g === void 0) { g = 0; }
  1451. if (b === void 0) { b = 0; }
  1452. this.r = r;
  1453. this.g = g;
  1454. this.b = b;
  1455. }
  1456. /**
  1457. * Creates a string with the Color3 current values
  1458. * @returns the string representation of the Color3 object
  1459. */
  1460. Color3.prototype.toString = function () {
  1461. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1462. };
  1463. /**
  1464. * Returns the string "Color3"
  1465. * @returns "Color3"
  1466. */
  1467. Color3.prototype.getClassName = function () {
  1468. return "Color3";
  1469. };
  1470. /**
  1471. * Compute the Color3 hash code
  1472. * @returns an unique number that can be used to hash Color3 objects
  1473. */
  1474. Color3.prototype.getHashCode = function () {
  1475. var hash = this.r || 0;
  1476. hash = (hash * 397) ^ (this.g || 0);
  1477. hash = (hash * 397) ^ (this.b || 0);
  1478. return hash;
  1479. };
  1480. // Operators
  1481. /**
  1482. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1483. * @param array defines the array where to store the r,g,b components
  1484. * @param index defines an optional index in the target array to define where to start storing values
  1485. * @returns the current Color3 object
  1486. */
  1487. Color3.prototype.toArray = function (array, index) {
  1488. if (index === undefined) {
  1489. index = 0;
  1490. }
  1491. array[index] = this.r;
  1492. array[index + 1] = this.g;
  1493. array[index + 2] = this.b;
  1494. return this;
  1495. };
  1496. /**
  1497. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1498. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1499. * @returns a new {BABYLON.Color4} object
  1500. */
  1501. Color3.prototype.toColor4 = function (alpha) {
  1502. if (alpha === void 0) { alpha = 1; }
  1503. return new Color4(this.r, this.g, this.b, alpha);
  1504. };
  1505. /**
  1506. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1507. * @returns the new array
  1508. */
  1509. Color3.prototype.asArray = function () {
  1510. var result = new Array();
  1511. this.toArray(result, 0);
  1512. return result;
  1513. };
  1514. /**
  1515. * Returns the luminance value
  1516. * @returns a float value
  1517. */
  1518. Color3.prototype.toLuminance = function () {
  1519. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1520. };
  1521. /**
  1522. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1523. * @param otherColor defines the second operand
  1524. * @returns the new Color3 object
  1525. */
  1526. Color3.prototype.multiply = function (otherColor) {
  1527. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1528. };
  1529. /**
  1530. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1531. * @param otherColor defines the second operand
  1532. * @param result defines the Color3 object where to store the result
  1533. * @returns the current Color3
  1534. */
  1535. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1536. result.r = this.r * otherColor.r;
  1537. result.g = this.g * otherColor.g;
  1538. result.b = this.b * otherColor.b;
  1539. return this;
  1540. };
  1541. /**
  1542. * Determines equality between Color3 objects
  1543. * @param otherColor defines the second operand
  1544. * @returns true if the rgb values are equal to the passed ones
  1545. */
  1546. Color3.prototype.equals = function (otherColor) {
  1547. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1548. };
  1549. /**
  1550. * Determines equality between the current Color3 object and a set of r,b,g values
  1551. * @param r defines the red component to check
  1552. * @param g defines the green component to check
  1553. * @param b defines the blue component to check
  1554. * @returns true if the rgb values are equal to the passed ones
  1555. */
  1556. Color3.prototype.equalsFloats = function (r, g, b) {
  1557. return this.r === r && this.g === g && this.b === b;
  1558. };
  1559. /**
  1560. * Multiplies in place each rgb value by scale
  1561. * @param scale defines the scaling factor
  1562. * @returns the updated Color3
  1563. */
  1564. Color3.prototype.scale = function (scale) {
  1565. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1566. };
  1567. /**
  1568. * Multiplies the rgb values by scale and stores the result into "result"
  1569. * @param scale defines the scaling factor
  1570. * @param result defines the Color3 object where to store the result
  1571. * @returns the unmodified current Color3
  1572. */
  1573. Color3.prototype.scaleToRef = function (scale, result) {
  1574. result.r = this.r * scale;
  1575. result.g = this.g * scale;
  1576. result.b = this.b * scale;
  1577. return this;
  1578. };
  1579. /**
  1580. * Scale the current Color3 values by a factor and add the result to a given Color3
  1581. * @param scale defines the scale factor
  1582. * @param result defines color to store the result into
  1583. * @returns the unmodified current Color3
  1584. */
  1585. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1586. result.r += this.r * scale;
  1587. result.g += this.g * scale;
  1588. result.b += this.b * scale;
  1589. return this;
  1590. };
  1591. /**
  1592. * Clamps the rgb values by the min and max values and stores the result into "result"
  1593. * @param min defines minimum clamping value (default is 0)
  1594. * @param max defines maximum clamping value (default is 1)
  1595. * @param result defines color to store the result into
  1596. * @returns the original Color3
  1597. */
  1598. Color3.prototype.clampToRef = function (min, max, result) {
  1599. if (min === void 0) { min = 0; }
  1600. if (max === void 0) { max = 1; }
  1601. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1602. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1603. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1604. return this;
  1605. };
  1606. /**
  1607. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1608. * @param otherColor defines the second operand
  1609. * @returns the new Color3
  1610. */
  1611. Color3.prototype.add = function (otherColor) {
  1612. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1613. };
  1614. /**
  1615. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1616. * @param otherColor defines the second operand
  1617. * @param result defines Color3 object to store the result into
  1618. * @returns the unmodified current Color3
  1619. */
  1620. Color3.prototype.addToRef = function (otherColor, result) {
  1621. result.r = this.r + otherColor.r;
  1622. result.g = this.g + otherColor.g;
  1623. result.b = this.b + otherColor.b;
  1624. return this;
  1625. };
  1626. /**
  1627. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1628. * @param otherColor defines the second operand
  1629. * @returns the new Color3
  1630. */
  1631. Color3.prototype.subtract = function (otherColor) {
  1632. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1633. };
  1634. /**
  1635. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1636. * @param otherColor defines the second operand
  1637. * @param result defines Color3 object to store the result into
  1638. * @returns the unmodified current Color3
  1639. */
  1640. Color3.prototype.subtractToRef = function (otherColor, result) {
  1641. result.r = this.r - otherColor.r;
  1642. result.g = this.g - otherColor.g;
  1643. result.b = this.b - otherColor.b;
  1644. return this;
  1645. };
  1646. /**
  1647. * Copy the current object
  1648. * @returns a new Color3 copied the current one
  1649. */
  1650. Color3.prototype.clone = function () {
  1651. return new Color3(this.r, this.g, this.b);
  1652. };
  1653. /**
  1654. * Copies the rgb values from the source in the current Color3
  1655. * @param source defines the source Color3 object
  1656. * @returns the updated Color3 object
  1657. */
  1658. Color3.prototype.copyFrom = function (source) {
  1659. this.r = source.r;
  1660. this.g = source.g;
  1661. this.b = source.b;
  1662. return this;
  1663. };
  1664. /**
  1665. * Updates the Color3 rgb values from the passed floats
  1666. * @param r defines the red component to read from
  1667. * @param g defines the green component to read from
  1668. * @param b defines the blue component to read from
  1669. * @returns the current Color3 object
  1670. */
  1671. Color3.prototype.copyFromFloats = function (r, g, b) {
  1672. this.r = r;
  1673. this.g = g;
  1674. this.b = b;
  1675. return this;
  1676. };
  1677. /**
  1678. * Updates the Color3 rgb values from the passed floats
  1679. * @param r defines the red component to read from
  1680. * @param g defines the green component to read from
  1681. * @param b defines the blue component to read from
  1682. * @returns the current Color3 object
  1683. */
  1684. Color3.prototype.set = function (r, g, b) {
  1685. return this.copyFromFloats(r, g, b);
  1686. };
  1687. /**
  1688. * Compute the Color3 hexadecimal code as a string
  1689. * @returns a string containing the hexadecimal representation of the Color3 object
  1690. */
  1691. Color3.prototype.toHexString = function () {
  1692. var intR = (this.r * 255) | 0;
  1693. var intG = (this.g * 255) | 0;
  1694. var intB = (this.b * 255) | 0;
  1695. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1696. };
  1697. /**
  1698. * Computes a new Color3 converted from the current one to linear space
  1699. * @returns a new Color3 object
  1700. */
  1701. Color3.prototype.toLinearSpace = function () {
  1702. var convertedColor = new Color3();
  1703. this.toLinearSpaceToRef(convertedColor);
  1704. return convertedColor;
  1705. };
  1706. /**
  1707. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1708. * @param convertedColor defines the Color3 object where to store the linear space version
  1709. * @returns the unmodified Color3
  1710. */
  1711. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1712. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1713. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1714. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1715. return this;
  1716. };
  1717. /**
  1718. * Computes a new Color3 converted from the current one to gamma space
  1719. * @returns a new Color3 object
  1720. */
  1721. Color3.prototype.toGammaSpace = function () {
  1722. var convertedColor = new Color3();
  1723. this.toGammaSpaceToRef(convertedColor);
  1724. return convertedColor;
  1725. };
  1726. /**
  1727. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1728. * @param convertedColor defines the Color3 object where to store the gamma space version
  1729. * @returns the unmodified Color3
  1730. */
  1731. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1732. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1733. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1734. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1735. return this;
  1736. };
  1737. // Statics
  1738. /**
  1739. * Creates a new Color3 from the string containing valid hexadecimal values
  1740. * @param hex defines a string containing valid hexadecimal values
  1741. * @returns a new Color3 object
  1742. */
  1743. Color3.FromHexString = function (hex) {
  1744. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1745. return new Color3(0, 0, 0);
  1746. }
  1747. var r = parseInt(hex.substring(1, 3), 16);
  1748. var g = parseInt(hex.substring(3, 5), 16);
  1749. var b = parseInt(hex.substring(5, 7), 16);
  1750. return Color3.FromInts(r, g, b);
  1751. };
  1752. /**
  1753. * Creates a new Vector3 from the starting index of the passed array
  1754. * @param array defines the source array
  1755. * @param offset defines an offset in the source array
  1756. * @returns a new Color3 object
  1757. */
  1758. Color3.FromArray = function (array, offset) {
  1759. if (offset === void 0) { offset = 0; }
  1760. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1761. };
  1762. /**
  1763. * Creates a new Color3 from integer values (< 256)
  1764. * @param r defines the red component to read from (value between 0 and 255)
  1765. * @param g defines the green component to read from (value between 0 and 255)
  1766. * @param b defines the blue component to read from (value between 0 and 255)
  1767. * @returns a new Color3 object
  1768. */
  1769. Color3.FromInts = function (r, g, b) {
  1770. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1771. };
  1772. /**
  1773. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1774. * @param start defines the start Color3 value
  1775. * @param end defines the end Color3 value
  1776. * @param amount defines the gradient value between start and end
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.Lerp = function (start, end, amount) {
  1780. var r = start.r + ((end.r - start.r) * amount);
  1781. var g = start.g + ((end.g - start.g) * amount);
  1782. var b = start.b + ((end.b - start.b) * amount);
  1783. return new Color3(r, g, b);
  1784. };
  1785. /**
  1786. * Returns a Color3 value containing a red color
  1787. * @returns a new Color3 object
  1788. */
  1789. Color3.Red = function () { return new Color3(1, 0, 0); };
  1790. /**
  1791. * Returns a Color3 value containing a green color
  1792. * @returns a new Color3 object
  1793. */
  1794. Color3.Green = function () { return new Color3(0, 1, 0); };
  1795. /**
  1796. * Returns a Color3 value containing a blue color
  1797. * @returns a new Color3 object
  1798. */
  1799. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1800. /**
  1801. * Returns a Color3 value containing a black color
  1802. * @returns a new Color3 object
  1803. */
  1804. Color3.Black = function () { return new Color3(0, 0, 0); };
  1805. /**
  1806. * Returns a Color3 value containing a white color
  1807. * @returns a new Color3 object
  1808. */
  1809. Color3.White = function () { return new Color3(1, 1, 1); };
  1810. /**
  1811. * Returns a Color3 value containing a purple color
  1812. * @returns a new Color3 object
  1813. */
  1814. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1815. /**
  1816. * Returns a Color3 value containing a magenta color
  1817. * @returns a new Color3 object
  1818. */
  1819. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1820. /**
  1821. * Returns a Color3 value containing a yellow color
  1822. * @returns a new Color3 object
  1823. */
  1824. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1825. /**
  1826. * Returns a Color3 value containing a gray color
  1827. * @returns a new Color3 object
  1828. */
  1829. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1830. /**
  1831. * Returns a Color3 value containing a teal color
  1832. * @returns a new Color3 object
  1833. */
  1834. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1835. /**
  1836. * Returns a Color3 value containing a random color
  1837. * @returns a new Color3 object
  1838. */
  1839. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1840. return Color3;
  1841. }());
  1842. BABYLON.Color3 = Color3;
  1843. /**
  1844. * Class used to hold a RBGA color
  1845. */
  1846. var Color4 = /** @class */ (function () {
  1847. /**
  1848. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1849. * @param r defines the red component (between 0 and 1, default is 0)
  1850. * @param g defines the green component (between 0 and 1, default is 0)
  1851. * @param b defines the blue component (between 0 and 1, default is 0)
  1852. * @param a defines the alpha component (between 0 and 1, default is 1)
  1853. */
  1854. function Color4(
  1855. /**
  1856. * Defines the red component (between 0 and 1, default is 0)
  1857. */
  1858. r,
  1859. /**
  1860. * Defines the green component (between 0 and 1, default is 0)
  1861. */
  1862. g,
  1863. /**
  1864. * Defines the blue component (between 0 and 1, default is 0)
  1865. */
  1866. b,
  1867. /**
  1868. * Defines the alpha component (between 0 and 1, default is 1)
  1869. */
  1870. a) {
  1871. if (r === void 0) { r = 0; }
  1872. if (g === void 0) { g = 0; }
  1873. if (b === void 0) { b = 0; }
  1874. if (a === void 0) { a = 1; }
  1875. this.r = r;
  1876. this.g = g;
  1877. this.b = b;
  1878. this.a = a;
  1879. }
  1880. // Operators
  1881. /**
  1882. * Adds in place the passed Color4 values to the current Color4 object
  1883. * @param right defines the second operand
  1884. * @returns the current updated Color4 object
  1885. */
  1886. Color4.prototype.addInPlace = function (right) {
  1887. this.r += right.r;
  1888. this.g += right.g;
  1889. this.b += right.b;
  1890. this.a += right.a;
  1891. return this;
  1892. };
  1893. /**
  1894. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1895. * @returns the new array
  1896. */
  1897. Color4.prototype.asArray = function () {
  1898. var result = new Array();
  1899. this.toArray(result, 0);
  1900. return result;
  1901. };
  1902. /**
  1903. * Stores from the starting index in the passed array the Color4 successive values
  1904. * @param array defines the array where to store the r,g,b components
  1905. * @param index defines an optional index in the target array to define where to start storing values
  1906. * @returns the current Color4 object
  1907. */
  1908. Color4.prototype.toArray = function (array, index) {
  1909. if (index === undefined) {
  1910. index = 0;
  1911. }
  1912. array[index] = this.r;
  1913. array[index + 1] = this.g;
  1914. array[index + 2] = this.b;
  1915. array[index + 3] = this.a;
  1916. return this;
  1917. };
  1918. /**
  1919. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1920. * @param right defines the second operand
  1921. * @returns a new Color4 object
  1922. */
  1923. Color4.prototype.add = function (right) {
  1924. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1925. };
  1926. /**
  1927. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1928. * @param right defines the second operand
  1929. * @returns a new Color4 object
  1930. */
  1931. Color4.prototype.subtract = function (right) {
  1932. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1933. };
  1934. /**
  1935. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1936. * @param right defines the second operand
  1937. * @param result defines the Color4 object where to store the result
  1938. * @returns the current Color4 object
  1939. */
  1940. Color4.prototype.subtractToRef = function (right, result) {
  1941. result.r = this.r - right.r;
  1942. result.g = this.g - right.g;
  1943. result.b = this.b - right.b;
  1944. result.a = this.a - right.a;
  1945. return this;
  1946. };
  1947. /**
  1948. * Creates a new Color4 with the current Color4 values multiplied by scale
  1949. * @param scale defines the scaling factor to apply
  1950. * @returns a new Color4 object
  1951. */
  1952. Color4.prototype.scale = function (scale) {
  1953. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1954. };
  1955. /**
  1956. * Multiplies the current Color4 values by scale and stores the result in "result"
  1957. * @param scale defines the scaling factor to apply
  1958. * @param result defines the Color4 object where to store the result
  1959. * @returns the current unmodified Color4
  1960. */
  1961. Color4.prototype.scaleToRef = function (scale, result) {
  1962. result.r = this.r * scale;
  1963. result.g = this.g * scale;
  1964. result.b = this.b * scale;
  1965. result.a = this.a * scale;
  1966. return this;
  1967. };
  1968. /**
  1969. * Scale the current Color4 values by a factor and add the result to a given Color4
  1970. * @param scale defines the scale factor
  1971. * @param result defines the Color4 object where to store the result
  1972. * @returns the unmodified current Color4
  1973. */
  1974. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1975. result.r += this.r * scale;
  1976. result.g += this.g * scale;
  1977. result.b += this.b * scale;
  1978. result.a += this.a * scale;
  1979. return this;
  1980. };
  1981. /**
  1982. * Clamps the rgb values by the min and max values and stores the result into "result"
  1983. * @param min defines minimum clamping value (default is 0)
  1984. * @param max defines maximum clamping value (default is 1)
  1985. * @param result defines color to store the result into.
  1986. * @returns the cuurent Color4
  1987. */
  1988. Color4.prototype.clampToRef = function (min, max, result) {
  1989. if (min === void 0) { min = 0; }
  1990. if (max === void 0) { max = 1; }
  1991. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1992. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1993. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1994. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1995. return this;
  1996. };
  1997. /**
  1998. * Multipy an Color4 value by another and return a new Color4 object
  1999. * @param color defines the Color4 value to multiply by
  2000. * @returns a new Color4 object
  2001. */
  2002. Color4.prototype.multiply = function (color) {
  2003. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2004. };
  2005. /**
  2006. * Multipy a Color4 value by another and push the result in a reference value
  2007. * @param color defines the Color4 value to multiply by
  2008. * @param result defines the Color4 to fill the result in
  2009. * @returns the result Color4
  2010. */
  2011. Color4.prototype.multiplyToRef = function (color, result) {
  2012. result.r = this.r * color.r;
  2013. result.g = this.g * color.g;
  2014. result.b = this.b * color.b;
  2015. result.a = this.a * color.a;
  2016. return result;
  2017. };
  2018. /**
  2019. * Creates a string with the Color4 current values
  2020. * @returns the string representation of the Color4 object
  2021. */
  2022. Color4.prototype.toString = function () {
  2023. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2024. };
  2025. /**
  2026. * Returns the string "Color4"
  2027. * @returns "Color4"
  2028. */
  2029. Color4.prototype.getClassName = function () {
  2030. return "Color4";
  2031. };
  2032. /**
  2033. * Compute the Color4 hash code
  2034. * @returns an unique number that can be used to hash Color4 objects
  2035. */
  2036. Color4.prototype.getHashCode = function () {
  2037. var hash = this.r || 0;
  2038. hash = (hash * 397) ^ (this.g || 0);
  2039. hash = (hash * 397) ^ (this.b || 0);
  2040. hash = (hash * 397) ^ (this.a || 0);
  2041. return hash;
  2042. };
  2043. /**
  2044. * Creates a new Color4 copied from the current one
  2045. * @returns a new Color4 object
  2046. */
  2047. Color4.prototype.clone = function () {
  2048. return new Color4(this.r, this.g, this.b, this.a);
  2049. };
  2050. /**
  2051. * Copies the passed Color4 values into the current one
  2052. * @param source defines the source Color4 object
  2053. * @returns the current updated Color4 object
  2054. */
  2055. Color4.prototype.copyFrom = function (source) {
  2056. this.r = source.r;
  2057. this.g = source.g;
  2058. this.b = source.b;
  2059. this.a = source.a;
  2060. return this;
  2061. };
  2062. /**
  2063. * Copies the passed float values into the current one
  2064. * @param r defines the red component to read from
  2065. * @param g defines the green component to read from
  2066. * @param b defines the blue component to read from
  2067. * @param a defines the alpha component to read from
  2068. * @returns the current updated Color4 object
  2069. */
  2070. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2071. this.r = r;
  2072. this.g = g;
  2073. this.b = b;
  2074. this.a = a;
  2075. return this;
  2076. };
  2077. /**
  2078. * Copies the passed float values into the current one
  2079. * @param r defines the red component to read from
  2080. * @param g defines the green component to read from
  2081. * @param b defines the blue component to read from
  2082. * @param a defines the alpha component to read from
  2083. * @returns the current updated Color4 object
  2084. */
  2085. Color4.prototype.set = function (r, g, b, a) {
  2086. return this.copyFromFloats(r, g, b, a);
  2087. };
  2088. /**
  2089. * Compute the Color4 hexadecimal code as a string
  2090. * @returns a string containing the hexadecimal representation of the Color4 object
  2091. */
  2092. Color4.prototype.toHexString = function () {
  2093. var intR = (this.r * 255) | 0;
  2094. var intG = (this.g * 255) | 0;
  2095. var intB = (this.b * 255) | 0;
  2096. var intA = (this.a * 255) | 0;
  2097. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2098. };
  2099. /**
  2100. * Computes a new Color4 converted from the current one to linear space
  2101. * @returns a new Color4 object
  2102. */
  2103. Color4.prototype.toLinearSpace = function () {
  2104. var convertedColor = new Color4();
  2105. this.toLinearSpaceToRef(convertedColor);
  2106. return convertedColor;
  2107. };
  2108. /**
  2109. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2110. * @param convertedColor defines the Color4 object where to store the linear space version
  2111. * @returns the unmodified Color4
  2112. */
  2113. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2114. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2115. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2116. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2117. convertedColor.a = this.a;
  2118. return this;
  2119. };
  2120. /**
  2121. * Computes a new Color4 converted from the current one to gamma space
  2122. * @returns a new Color4 object
  2123. */
  2124. Color4.prototype.toGammaSpace = function () {
  2125. var convertedColor = new Color4();
  2126. this.toGammaSpaceToRef(convertedColor);
  2127. return convertedColor;
  2128. };
  2129. /**
  2130. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2131. * @param convertedColor defines the Color4 object where to store the gamma space version
  2132. * @returns the unmodified Color4
  2133. */
  2134. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2135. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2136. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2137. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2138. convertedColor.a = this.a;
  2139. return this;
  2140. };
  2141. // Statics
  2142. /**
  2143. * Creates a new Color4 from the string containing valid hexadecimal values
  2144. * @param hex defines a string containing valid hexadecimal values
  2145. * @returns a new Color4 object
  2146. */
  2147. Color4.FromHexString = function (hex) {
  2148. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2149. return new Color4(0.0, 0.0, 0.0, 0.0);
  2150. }
  2151. var r = parseInt(hex.substring(1, 3), 16);
  2152. var g = parseInt(hex.substring(3, 5), 16);
  2153. var b = parseInt(hex.substring(5, 7), 16);
  2154. var a = parseInt(hex.substring(7, 9), 16);
  2155. return Color4.FromInts(r, g, b, a);
  2156. };
  2157. /**
  2158. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2159. * @param left defines the start value
  2160. * @param right defines the end value
  2161. * @param amount defines the gradient factor
  2162. * @returns a new Color4 object
  2163. */
  2164. Color4.Lerp = function (left, right, amount) {
  2165. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2166. Color4.LerpToRef(left, right, amount, result);
  2167. return result;
  2168. };
  2169. /**
  2170. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2171. * @param left defines the start value
  2172. * @param right defines the end value
  2173. * @param amount defines the gradient factor
  2174. * @param result defines the Color4 object where to store data
  2175. */
  2176. Color4.LerpToRef = function (left, right, amount, result) {
  2177. result.r = left.r + (right.r - left.r) * amount;
  2178. result.g = left.g + (right.g - left.g) * amount;
  2179. result.b = left.b + (right.b - left.b) * amount;
  2180. result.a = left.a + (right.a - left.a) * amount;
  2181. };
  2182. /**
  2183. * Creates a new Color4 from the starting index element of the passed array
  2184. * @param array defines the source array to read from
  2185. * @param offset defines the offset in the source array
  2186. * @returns a new Color4 object
  2187. */
  2188. Color4.FromArray = function (array, offset) {
  2189. if (offset === void 0) { offset = 0; }
  2190. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2191. };
  2192. /**
  2193. * Creates a new Color3 from integer values (< 256)
  2194. * @param r defines the red component to read from (value between 0 and 255)
  2195. * @param g defines the green component to read from (value between 0 and 255)
  2196. * @param b defines the blue component to read from (value between 0 and 255)
  2197. * @param a defines the alpha component to read from (value between 0 and 255)
  2198. * @returns a new Color3 object
  2199. */
  2200. Color4.FromInts = function (r, g, b, a) {
  2201. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2202. };
  2203. /**
  2204. * Check the content of a given array and convert it to an array containing RGBA data
  2205. * If the original array was already containing count * 4 values then it is returned directly
  2206. * @param colors defines the array to check
  2207. * @param count defines the number of RGBA data to expect
  2208. * @returns an array containing count * 4 values (RGBA)
  2209. */
  2210. Color4.CheckColors4 = function (colors, count) {
  2211. // Check if color3 was used
  2212. if (colors.length === count * 3) {
  2213. var colors4 = [];
  2214. for (var index = 0; index < colors.length; index += 3) {
  2215. var newIndex = (index / 3) * 4;
  2216. colors4[newIndex] = colors[index];
  2217. colors4[newIndex + 1] = colors[index + 1];
  2218. colors4[newIndex + 2] = colors[index + 2];
  2219. colors4[newIndex + 3] = 1.0;
  2220. }
  2221. return colors4;
  2222. }
  2223. return colors;
  2224. };
  2225. return Color4;
  2226. }());
  2227. BABYLON.Color4 = Color4;
  2228. var Vector2 = /** @class */ (function () {
  2229. /**
  2230. * Creates a new Vector2 from the passed x and y coordinates.
  2231. */
  2232. function Vector2(x, y) {
  2233. this.x = x;
  2234. this.y = y;
  2235. }
  2236. /**
  2237. * Returns a string with the Vector2 coordinates.
  2238. */
  2239. Vector2.prototype.toString = function () {
  2240. return "{X: " + this.x + " Y:" + this.y + "}";
  2241. };
  2242. /**
  2243. * Returns the string "Vector2"
  2244. */
  2245. Vector2.prototype.getClassName = function () {
  2246. return "Vector2";
  2247. };
  2248. /**
  2249. * Returns the Vector2 hash code as a number.
  2250. */
  2251. Vector2.prototype.getHashCode = function () {
  2252. var hash = this.x || 0;
  2253. hash = (hash * 397) ^ (this.y || 0);
  2254. return hash;
  2255. };
  2256. // Operators
  2257. /**
  2258. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2259. * Returns the Vector2.
  2260. */
  2261. Vector2.prototype.toArray = function (array, index) {
  2262. if (index === void 0) { index = 0; }
  2263. array[index] = this.x;
  2264. array[index + 1] = this.y;
  2265. return this;
  2266. };
  2267. /**
  2268. * Returns a new array with 2 elements : the Vector2 coordinates.
  2269. */
  2270. Vector2.prototype.asArray = function () {
  2271. var result = new Array();
  2272. this.toArray(result, 0);
  2273. return result;
  2274. };
  2275. /**
  2276. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2277. * Returns the updated Vector2.
  2278. */
  2279. Vector2.prototype.copyFrom = function (source) {
  2280. this.x = source.x;
  2281. this.y = source.y;
  2282. return this;
  2283. };
  2284. /**
  2285. * Sets the Vector2 coordinates with the passed floats.
  2286. * Returns the updated Vector2.
  2287. */
  2288. Vector2.prototype.copyFromFloats = function (x, y) {
  2289. this.x = x;
  2290. this.y = y;
  2291. return this;
  2292. };
  2293. /**
  2294. * Sets the Vector2 coordinates with the passed floats.
  2295. * Returns the updated Vector2.
  2296. */
  2297. Vector2.prototype.set = function (x, y) {
  2298. return this.copyFromFloats(x, y);
  2299. };
  2300. /**
  2301. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2302. */
  2303. Vector2.prototype.add = function (otherVector) {
  2304. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2305. };
  2306. /**
  2307. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2308. * Returns the 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 passed Vector2 coordinates.
  2317. * Returns the updated Vector2.
  2318. */
  2319. Vector2.prototype.addInPlace = function (otherVector) {
  2320. this.x += otherVector.x;
  2321. this.y += otherVector.y;
  2322. return this;
  2323. };
  2324. /**
  2325. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2326. */
  2327. Vector2.prototype.addVector3 = function (otherVector) {
  2328. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2329. };
  2330. /**
  2331. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2332. */
  2333. Vector2.prototype.subtract = function (otherVector) {
  2334. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2335. };
  2336. /**
  2337. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2338. * Returns the Vector2.
  2339. */
  2340. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2341. result.x = this.x - otherVector.x;
  2342. result.y = this.y - otherVector.y;
  2343. return this;
  2344. };
  2345. /**
  2346. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2347. * Returns the updated Vector2.
  2348. */
  2349. Vector2.prototype.subtractInPlace = function (otherVector) {
  2350. this.x -= otherVector.x;
  2351. this.y -= otherVector.y;
  2352. return this;
  2353. };
  2354. /**
  2355. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2356. * Returns the updated Vector2.
  2357. */
  2358. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2359. this.x *= otherVector.x;
  2360. this.y *= otherVector.y;
  2361. return this;
  2362. };
  2363. /**
  2364. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2365. */
  2366. Vector2.prototype.multiply = function (otherVector) {
  2367. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2368. };
  2369. /**
  2370. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2371. * Returns the Vector2.
  2372. */
  2373. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2374. result.x = this.x * otherVector.x;
  2375. result.y = this.y * otherVector.y;
  2376. return this;
  2377. };
  2378. /**
  2379. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2380. */
  2381. Vector2.prototype.multiplyByFloats = function (x, y) {
  2382. return new Vector2(this.x * x, this.y * y);
  2383. };
  2384. /**
  2385. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2386. */
  2387. Vector2.prototype.divide = function (otherVector) {
  2388. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2389. };
  2390. /**
  2391. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2392. * Returns the Vector2.
  2393. */
  2394. Vector2.prototype.divideToRef = function (otherVector, result) {
  2395. result.x = this.x / otherVector.x;
  2396. result.y = this.y / otherVector.y;
  2397. return this;
  2398. };
  2399. /**
  2400. * Divides the current Vector3 coordinates by the passed ones.
  2401. * Returns the updated Vector3.
  2402. */
  2403. Vector2.prototype.divideInPlace = function (otherVector) {
  2404. return this.divideToRef(otherVector, this);
  2405. };
  2406. /**
  2407. * Returns a new Vector2 with current Vector2 negated coordinates.
  2408. */
  2409. Vector2.prototype.negate = function () {
  2410. return new Vector2(-this.x, -this.y);
  2411. };
  2412. /**
  2413. * Multiply the Vector2 coordinates by scale.
  2414. * Returns the updated Vector2.
  2415. */
  2416. Vector2.prototype.scaleInPlace = function (scale) {
  2417. this.x *= scale;
  2418. this.y *= scale;
  2419. return this;
  2420. };
  2421. /**
  2422. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2423. */
  2424. Vector2.prototype.scale = function (scale) {
  2425. var result = new Vector2(0, 0);
  2426. this.scaleToRef(scale, result);
  2427. return result;
  2428. };
  2429. /**
  2430. * Scale the current Vector2 values by a factor to a given Vector2
  2431. * @param scale defines the scale factor
  2432. * @param result defines the Vector2 object where to store the result
  2433. * @returns the unmodified current Vector2
  2434. */
  2435. Vector2.prototype.scaleToRef = function (scale, result) {
  2436. result.x = this.x * scale;
  2437. result.y = this.y * scale;
  2438. return this;
  2439. };
  2440. /**
  2441. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2442. * @param scale defines the scale factor
  2443. * @param result defines the Vector2 object where to store the result
  2444. * @returns the unmodified current Vector2
  2445. */
  2446. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2447. result.x += this.x * scale;
  2448. result.y += this.y * scale;
  2449. return this;
  2450. };
  2451. /**
  2452. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2453. */
  2454. Vector2.prototype.equals = function (otherVector) {
  2455. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2456. };
  2457. /**
  2458. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2459. */
  2460. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2461. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2462. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2463. };
  2464. // Properties
  2465. /**
  2466. * Returns the vector length (float).
  2467. */
  2468. Vector2.prototype.length = function () {
  2469. return Math.sqrt(this.x * this.x + this.y * this.y);
  2470. };
  2471. /**
  2472. * Returns the vector squared length (float);
  2473. */
  2474. Vector2.prototype.lengthSquared = function () {
  2475. return (this.x * this.x + this.y * this.y);
  2476. };
  2477. // Methods
  2478. /**
  2479. * Normalize the vector.
  2480. * Returns the updated Vector2.
  2481. */
  2482. Vector2.prototype.normalize = function () {
  2483. var len = this.length();
  2484. if (len === 0)
  2485. return this;
  2486. var num = 1.0 / len;
  2487. this.x *= num;
  2488. this.y *= num;
  2489. return this;
  2490. };
  2491. /**
  2492. * Returns a new Vector2 copied from the Vector2.
  2493. */
  2494. Vector2.prototype.clone = function () {
  2495. return new Vector2(this.x, this.y);
  2496. };
  2497. // Statics
  2498. /**
  2499. * Returns a new Vector2(0, 0)
  2500. */
  2501. Vector2.Zero = function () {
  2502. return new Vector2(0, 0);
  2503. };
  2504. /**
  2505. * Returns a new Vector2(1, 1)
  2506. */
  2507. Vector2.One = function () {
  2508. return new Vector2(1, 1);
  2509. };
  2510. /**
  2511. * Returns a new Vector2 set from the passed index element of the passed array.
  2512. */
  2513. Vector2.FromArray = function (array, offset) {
  2514. if (offset === void 0) { offset = 0; }
  2515. return new Vector2(array[offset], array[offset + 1]);
  2516. };
  2517. /**
  2518. * Sets "result" from the passed index element of the passed array.
  2519. */
  2520. Vector2.FromArrayToRef = function (array, offset, result) {
  2521. result.x = array[offset];
  2522. result.y = array[offset + 1];
  2523. };
  2524. /**
  2525. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2526. */
  2527. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2528. var squared = amount * amount;
  2529. var cubed = amount * squared;
  2530. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2531. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2532. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2533. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2534. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2535. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2536. return new Vector2(x, y);
  2537. };
  2538. /**
  2539. * 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".
  2540. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2541. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2542. */
  2543. Vector2.Clamp = function (value, min, max) {
  2544. var x = value.x;
  2545. x = (x > max.x) ? max.x : x;
  2546. x = (x < min.x) ? min.x : x;
  2547. var y = value.y;
  2548. y = (y > max.y) ? max.y : y;
  2549. y = (y < min.y) ? min.y : y;
  2550. return new Vector2(x, y);
  2551. };
  2552. /**
  2553. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2554. */
  2555. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2556. var squared = amount * amount;
  2557. var cubed = amount * squared;
  2558. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2559. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2560. var part3 = (cubed - (2.0 * squared)) + amount;
  2561. var part4 = cubed - squared;
  2562. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2563. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2564. return new Vector2(x, y);
  2565. };
  2566. /**
  2567. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2568. */
  2569. Vector2.Lerp = function (start, end, amount) {
  2570. var x = start.x + ((end.x - start.x) * amount);
  2571. var y = start.y + ((end.y - start.y) * amount);
  2572. return new Vector2(x, y);
  2573. };
  2574. /**
  2575. * Returns the dot product (float) of the vector "left" and the vector "right".
  2576. */
  2577. Vector2.Dot = function (left, right) {
  2578. return left.x * right.x + left.y * right.y;
  2579. };
  2580. /**
  2581. * Returns a new Vector2 equal to the normalized passed vector.
  2582. */
  2583. Vector2.Normalize = function (vector) {
  2584. var newVector = vector.clone();
  2585. newVector.normalize();
  2586. return newVector;
  2587. };
  2588. /**
  2589. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2590. */
  2591. Vector2.Minimize = function (left, right) {
  2592. var x = (left.x < right.x) ? left.x : right.x;
  2593. var y = (left.y < right.y) ? left.y : right.y;
  2594. return new Vector2(x, y);
  2595. };
  2596. /**
  2597. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2598. */
  2599. Vector2.Maximize = function (left, right) {
  2600. var x = (left.x > right.x) ? left.x : right.x;
  2601. var y = (left.y > right.y) ? left.y : right.y;
  2602. return new Vector2(x, y);
  2603. };
  2604. /**
  2605. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2606. */
  2607. Vector2.Transform = function (vector, transformation) {
  2608. var r = Vector2.Zero();
  2609. Vector2.TransformToRef(vector, transformation, r);
  2610. return r;
  2611. };
  2612. /**
  2613. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2614. */
  2615. Vector2.TransformToRef = function (vector, transformation, result) {
  2616. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2617. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2618. result.x = x;
  2619. result.y = y;
  2620. };
  2621. /**
  2622. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2623. */
  2624. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2625. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2626. var sign = a < 0 ? -1 : 1;
  2627. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2628. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2629. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2630. };
  2631. /**
  2632. * Returns the distance (float) between the vectors "value1" and "value2".
  2633. */
  2634. Vector2.Distance = function (value1, value2) {
  2635. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2636. };
  2637. /**
  2638. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2639. */
  2640. Vector2.DistanceSquared = function (value1, value2) {
  2641. var x = value1.x - value2.x;
  2642. var y = value1.y - value2.y;
  2643. return (x * x) + (y * y);
  2644. };
  2645. /**
  2646. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2647. */
  2648. Vector2.Center = function (value1, value2) {
  2649. var center = value1.add(value2);
  2650. center.scaleInPlace(0.5);
  2651. return center;
  2652. };
  2653. /**
  2654. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2655. */
  2656. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2657. var l2 = Vector2.DistanceSquared(segA, segB);
  2658. if (l2 === 0.0) {
  2659. return Vector2.Distance(p, segA);
  2660. }
  2661. var v = segB.subtract(segA);
  2662. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2663. var proj = segA.add(v.multiplyByFloats(t, t));
  2664. return Vector2.Distance(p, proj);
  2665. };
  2666. return Vector2;
  2667. }());
  2668. BABYLON.Vector2 = Vector2;
  2669. /**
  2670. * Classed used to store (x,y,z) vector representation
  2671. * A Vector3 is the main object used in 3D geometry
  2672. * It can represent etiher the coordinates of a point the space, either a direction
  2673. * Reminder: Babylon.js uses a left handed forward facing system
  2674. */
  2675. var Vector3 = /** @class */ (function () {
  2676. /**
  2677. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2678. * @param x defines the first coordinates (on X axis)
  2679. * @param y defines the second coordinates (on Y axis)
  2680. * @param z defines the third coordinates (on Z axis)
  2681. */
  2682. function Vector3(
  2683. /**
  2684. * Defines the first coordinates (on X axis)
  2685. */
  2686. x,
  2687. /**
  2688. * Defines the second coordinates (on Y axis)
  2689. */
  2690. y,
  2691. /**
  2692. * Defines the third coordinates (on Z axis)
  2693. */
  2694. z) {
  2695. this.x = x;
  2696. this.y = y;
  2697. this.z = z;
  2698. }
  2699. /**
  2700. * Creates a string representation of the Vector3
  2701. * @returns a string with the Vector3 coordinates.
  2702. */
  2703. Vector3.prototype.toString = function () {
  2704. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2705. };
  2706. /**
  2707. * Gets the class name
  2708. * @returns the string "Vector3"
  2709. */
  2710. Vector3.prototype.getClassName = function () {
  2711. return "Vector3";
  2712. };
  2713. /**
  2714. * Creates the Vector3 hash code
  2715. * @returns a number which tends to be unique between Vector3 instances
  2716. */
  2717. Vector3.prototype.getHashCode = function () {
  2718. var hash = this.x || 0;
  2719. hash = (hash * 397) ^ (this.y || 0);
  2720. hash = (hash * 397) ^ (this.z || 0);
  2721. return hash;
  2722. };
  2723. // Operators
  2724. /**
  2725. * Creates an array containing three elements : the coordinates of the Vector3
  2726. * @returns a new array of numbers
  2727. */
  2728. Vector3.prototype.asArray = function () {
  2729. var result = [];
  2730. this.toArray(result, 0);
  2731. return result;
  2732. };
  2733. /**
  2734. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2735. * @param array defines the destination array
  2736. * @param index defines the offset in the destination array
  2737. * @returns the current Vector3
  2738. */
  2739. Vector3.prototype.toArray = function (array, index) {
  2740. if (index === void 0) { index = 0; }
  2741. array[index] = this.x;
  2742. array[index + 1] = this.y;
  2743. array[index + 2] = this.z;
  2744. return this;
  2745. };
  2746. /**
  2747. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2748. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2749. */
  2750. Vector3.prototype.toQuaternion = function () {
  2751. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2752. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2753. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2754. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2755. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2756. var cosy = Math.cos(this.y * 0.5);
  2757. var siny = Math.sin(this.y * 0.5);
  2758. result.x = coszMinusx * siny;
  2759. result.y = -sinzMinusx * siny;
  2760. result.z = sinxPlusz * cosy;
  2761. result.w = cosxPlusz * cosy;
  2762. return result;
  2763. };
  2764. /**
  2765. * Adds the passed vector to the current Vector3
  2766. * @param otherVector defines the second operand
  2767. * @returns the current updated Vector3
  2768. */
  2769. Vector3.prototype.addInPlace = function (otherVector) {
  2770. this.x += otherVector.x;
  2771. this.y += otherVector.y;
  2772. this.z += otherVector.z;
  2773. return this;
  2774. };
  2775. /**
  2776. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2777. * @param otherVector defines the second operand
  2778. * @returns the resulting Vector3
  2779. */
  2780. Vector3.prototype.add = function (otherVector) {
  2781. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2782. };
  2783. /**
  2784. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2785. * @param otherVector defines the second operand
  2786. * @param result defines the Vector3 object where to store the result
  2787. * @returns the current Vector3
  2788. */
  2789. Vector3.prototype.addToRef = function (otherVector, result) {
  2790. result.x = this.x + otherVector.x;
  2791. result.y = this.y + otherVector.y;
  2792. result.z = this.z + otherVector.z;
  2793. return this;
  2794. };
  2795. /**
  2796. * Subtract the passed vector from the current Vector3
  2797. * @param otherVector defines the second operand
  2798. * @returns the current updated Vector3
  2799. */
  2800. Vector3.prototype.subtractInPlace = function (otherVector) {
  2801. this.x -= otherVector.x;
  2802. this.y -= otherVector.y;
  2803. this.z -= otherVector.z;
  2804. return this;
  2805. };
  2806. /**
  2807. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2808. * @param otherVector defines the second operand
  2809. * @returns the resulting Vector3
  2810. */
  2811. Vector3.prototype.subtract = function (otherVector) {
  2812. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2813. };
  2814. /**
  2815. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2816. * @param otherVector defines the second operand
  2817. * @param result defines the Vector3 object where to store the result
  2818. * @returns the current Vector3
  2819. */
  2820. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2821. result.x = this.x - otherVector.x;
  2822. result.y = this.y - otherVector.y;
  2823. result.z = this.z - otherVector.z;
  2824. return this;
  2825. };
  2826. /**
  2827. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2828. * @param x defines the x coordinate of the operand
  2829. * @param y defines the y coordinate of the operand
  2830. * @param z defines the z coordinate of the operand
  2831. * @returns the resulting Vector3
  2832. */
  2833. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2834. return new Vector3(this.x - x, this.y - y, this.z - z);
  2835. };
  2836. /**
  2837. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2838. * @param x defines the x coordinate of the operand
  2839. * @param y defines the y coordinate of the operand
  2840. * @param z defines the z coordinate of the operand
  2841. * @param result defines the Vector3 object where to store the result
  2842. * @returns the current Vector3
  2843. */
  2844. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2845. result.x = this.x - x;
  2846. result.y = this.y - y;
  2847. result.z = this.z - z;
  2848. return this;
  2849. };
  2850. /**
  2851. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2852. * @returns a new Vector3
  2853. */
  2854. Vector3.prototype.negate = function () {
  2855. return new Vector3(-this.x, -this.y, -this.z);
  2856. };
  2857. /**
  2858. * Multiplies the Vector3 coordinates by the float "scale"
  2859. * @param scale defines the multiplier factor
  2860. * @returns the current updated Vector3
  2861. */
  2862. Vector3.prototype.scaleInPlace = function (scale) {
  2863. this.x *= scale;
  2864. this.y *= scale;
  2865. this.z *= scale;
  2866. return this;
  2867. };
  2868. /**
  2869. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2870. * @param scale defines the multiplier factor
  2871. * @returns a new Vector3
  2872. */
  2873. Vector3.prototype.scale = function (scale) {
  2874. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2875. };
  2876. /**
  2877. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2878. * @param scale defines the multiplier factor
  2879. * @param result defines the Vector3 object where to store the result
  2880. * @returns the current Vector3
  2881. */
  2882. Vector3.prototype.scaleToRef = function (scale, result) {
  2883. result.x = this.x * scale;
  2884. result.y = this.y * scale;
  2885. result.z = this.z * scale;
  2886. return this;
  2887. };
  2888. /**
  2889. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2890. * @param scale defines the scale factor
  2891. * @param result defines the Vector3 object where to store the result
  2892. * @returns the unmodified current Vector3
  2893. */
  2894. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2895. result.x += this.x * scale;
  2896. result.y += this.y * scale;
  2897. result.z += this.z * scale;
  2898. return this;
  2899. };
  2900. /**
  2901. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2902. * @param otherVector defines the second operand
  2903. * @returns true if both vectors are equals
  2904. */
  2905. Vector3.prototype.equals = function (otherVector) {
  2906. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2907. };
  2908. /**
  2909. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2910. * @param otherVector defines the second operand
  2911. * @param epsilon defines the minimal distance to define values as equals
  2912. * @returns true if both vectors are distant less than epsilon
  2913. */
  2914. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2915. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2916. 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);
  2917. };
  2918. /**
  2919. * Returns true if the current Vector3 coordinates equals the passed floats
  2920. * @param x defines the x coordinate of the operand
  2921. * @param y defines the y coordinate of the operand
  2922. * @param z defines the z coordinate of the operand
  2923. * @returns true if both vectors are equals
  2924. */
  2925. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2926. return this.x === x && this.y === y && this.z === z;
  2927. };
  2928. /**
  2929. * Multiplies the current Vector3 coordinates by the passed ones
  2930. * @param otherVector defines the second operand
  2931. * @returns the current updated Vector3
  2932. */
  2933. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2934. this.x *= otherVector.x;
  2935. this.y *= otherVector.y;
  2936. this.z *= otherVector.z;
  2937. return this;
  2938. };
  2939. /**
  2940. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2941. * @param otherVector defines the second operand
  2942. * @returns the new Vector3
  2943. */
  2944. Vector3.prototype.multiply = function (otherVector) {
  2945. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2946. };
  2947. /**
  2948. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2949. * @param otherVector defines the second operand
  2950. * @param result defines the Vector3 object where to store the result
  2951. * @returns the current Vector3
  2952. */
  2953. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2954. result.x = this.x * otherVector.x;
  2955. result.y = this.y * otherVector.y;
  2956. result.z = this.z * otherVector.z;
  2957. return this;
  2958. };
  2959. /**
  2960. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2961. * @param x defines the x coordinate of the operand
  2962. * @param y defines the y coordinate of the operand
  2963. * @param z defines the z coordinate of the operand
  2964. * @returns the new Vector3
  2965. */
  2966. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2967. return new Vector3(this.x * x, this.y * y, this.z * z);
  2968. };
  2969. /**
  2970. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2971. * @param otherVector defines the second operand
  2972. * @returns the new Vector3
  2973. */
  2974. Vector3.prototype.divide = function (otherVector) {
  2975. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2976. };
  2977. /**
  2978. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2979. * @param otherVector defines the second operand
  2980. * @param result defines the Vector3 object where to store the result
  2981. * @returns the current Vector3
  2982. */
  2983. Vector3.prototype.divideToRef = function (otherVector, result) {
  2984. result.x = this.x / otherVector.x;
  2985. result.y = this.y / otherVector.y;
  2986. result.z = this.z / otherVector.z;
  2987. return this;
  2988. };
  2989. /**
  2990. * Divides the current Vector3 coordinates by the passed ones.
  2991. * @param otherVector defines the second operand
  2992. * @returns the current updated Vector3
  2993. */
  2994. Vector3.prototype.divideInPlace = function (otherVector) {
  2995. return this.divideToRef(otherVector, this);
  2996. };
  2997. /**
  2998. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2999. * @param other defines the second operand
  3000. * @returns the current updated Vector3
  3001. */
  3002. Vector3.prototype.minimizeInPlace = function (other) {
  3003. if (other.x < this.x)
  3004. this.x = other.x;
  3005. if (other.y < this.y)
  3006. this.y = other.y;
  3007. if (other.z < this.z)
  3008. this.z = other.z;
  3009. return this;
  3010. };
  3011. /**
  3012. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  3013. * @param other defines the second operand
  3014. * @returns the current updated Vector3
  3015. */
  3016. Vector3.prototype.maximizeInPlace = function (other) {
  3017. if (other.x > this.x)
  3018. this.x = other.x;
  3019. if (other.y > this.y)
  3020. this.y = other.y;
  3021. if (other.z > this.z)
  3022. this.z = other.z;
  3023. return this;
  3024. };
  3025. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3026. /**
  3027. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3028. */
  3029. get: function () {
  3030. var absX = Math.abs(this.x);
  3031. var absY = Math.abs(this.y);
  3032. if (absX !== absY) {
  3033. return true;
  3034. }
  3035. var absZ = Math.abs(this.z);
  3036. if (absX !== absZ) {
  3037. return true;
  3038. }
  3039. if (absY !== absZ) {
  3040. return true;
  3041. }
  3042. return false;
  3043. },
  3044. enumerable: true,
  3045. configurable: true
  3046. });
  3047. // Properties
  3048. /**
  3049. * Gets the length of the Vector3
  3050. * @returns the length of the Vecto3
  3051. */
  3052. Vector3.prototype.length = function () {
  3053. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3054. };
  3055. /**
  3056. * Gets the squared length of the Vector3
  3057. * @returns squared length of the Vector3
  3058. */
  3059. Vector3.prototype.lengthSquared = function () {
  3060. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3061. };
  3062. /**
  3063. * Normalize the current Vector3.
  3064. * Please note that this is an in place operation.
  3065. * @returns the current updated Vector3
  3066. */
  3067. Vector3.prototype.normalize = function () {
  3068. var len = this.length();
  3069. if (len === 0 || len === 1.0)
  3070. return this;
  3071. var num = 1.0 / len;
  3072. this.x *= num;
  3073. this.y *= num;
  3074. this.z *= num;
  3075. return this;
  3076. };
  3077. /**
  3078. * Normalize the current Vector3 to a new vector
  3079. * @returns the new Vector3
  3080. */
  3081. Vector3.prototype.normalizeToNew = function () {
  3082. var normalized = new Vector3(0, 0, 0);
  3083. this.normalizeToRef(normalized);
  3084. return normalized;
  3085. };
  3086. /**
  3087. * Normalize the current Vector3 to the reference
  3088. * @param reference define the Vector3 to update
  3089. * @returns the updated Vector3
  3090. */
  3091. Vector3.prototype.normalizeToRef = function (reference) {
  3092. var len = this.length();
  3093. if (len === 0 || len === 1.0) {
  3094. reference.set(this.x, this.y, this.z);
  3095. return reference;
  3096. }
  3097. var scale = 1.0 / len;
  3098. this.scaleToRef(scale, reference);
  3099. return reference;
  3100. };
  3101. /**
  3102. * Creates a new Vector3 copied from the current Vector3
  3103. * @returns the new Vector3
  3104. */
  3105. Vector3.prototype.clone = function () {
  3106. return new Vector3(this.x, this.y, this.z);
  3107. };
  3108. /**
  3109. * Copies the passed vector coordinates to the current Vector3 ones
  3110. * @param source defines the source Vector3
  3111. * @returns the current updated Vector3
  3112. */
  3113. Vector3.prototype.copyFrom = function (source) {
  3114. this.x = source.x;
  3115. this.y = source.y;
  3116. this.z = source.z;
  3117. return this;
  3118. };
  3119. /**
  3120. * Copies the passed floats to the current Vector3 coordinates
  3121. * @param x defines the x coordinate of the operand
  3122. * @param y defines the y coordinate of the operand
  3123. * @param z defines the z coordinate of the operand
  3124. * @returns the current updated Vector3
  3125. */
  3126. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3127. this.x = x;
  3128. this.y = y;
  3129. this.z = z;
  3130. return this;
  3131. };
  3132. /**
  3133. * Copies the passed floats to the current Vector3 coordinates
  3134. * @param x defines the x coordinate of the operand
  3135. * @param y defines the y coordinate of the operand
  3136. * @param z defines the z coordinate of the operand
  3137. * @returns the current updated Vector3
  3138. */
  3139. Vector3.prototype.set = function (x, y, z) {
  3140. return this.copyFromFloats(x, y, z);
  3141. };
  3142. // Statics
  3143. /**
  3144. * Get the clip factor between two vectors
  3145. * @param vector0 defines the first operand
  3146. * @param vector1 defines the second operand
  3147. * @param axis defines the axis to use
  3148. * @param size defines the size along the axis
  3149. * @returns the clip factor
  3150. */
  3151. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3152. var d0 = Vector3.Dot(vector0, axis) - size;
  3153. var d1 = Vector3.Dot(vector1, axis) - size;
  3154. var s = d0 / (d0 - d1);
  3155. return s;
  3156. };
  3157. /**
  3158. * Get angle between two vectors
  3159. * @param vector0 angle between vector0 and vector1
  3160. * @param vector1 angle between vector0 and vector1
  3161. * @param normal direction of the normal
  3162. * @return the angle between vector0 and vector1
  3163. */
  3164. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3165. var v0 = vector0.clone().normalize();
  3166. var v1 = vector1.clone().normalize();
  3167. var dot = Vector3.Dot(v0, v1);
  3168. var n = Vector3.Cross(v0, v1);
  3169. if (Vector3.Dot(n, normal) > 0) {
  3170. return Math.acos(dot);
  3171. }
  3172. return -Math.acos(dot);
  3173. };
  3174. /**
  3175. * Returns a new Vector3 set from the index "offset" of the passed array
  3176. * @param array defines the source array
  3177. * @param offset defines the offset in the source array
  3178. * @returns the new Vector3
  3179. */
  3180. Vector3.FromArray = function (array, offset) {
  3181. if (!offset) {
  3182. offset = 0;
  3183. }
  3184. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3185. };
  3186. /**
  3187. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3188. * This function is deprecated. Use FromArray instead
  3189. * @param array defines the source array
  3190. * @param offset defines the offset in the source array
  3191. * @returns the new Vector3
  3192. */
  3193. Vector3.FromFloatArray = function (array, offset) {
  3194. return Vector3.FromArray(array, offset);
  3195. };
  3196. /**
  3197. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3198. * @param array defines the source array
  3199. * @param offset defines the offset in the source array
  3200. * @param result defines the Vector3 where to store the result
  3201. */
  3202. Vector3.FromArrayToRef = function (array, offset, result) {
  3203. result.x = array[offset];
  3204. result.y = array[offset + 1];
  3205. result.z = array[offset + 2];
  3206. };
  3207. /**
  3208. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3209. * This function is deprecated. Use FromArrayToRef instead.
  3210. * @param array defines the source array
  3211. * @param offset defines the offset in the source array
  3212. * @param result defines the Vector3 where to store the result
  3213. */
  3214. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3215. return Vector3.FromArrayToRef(array, offset, result);
  3216. };
  3217. /**
  3218. * Sets the passed vector "result" with the passed floats.
  3219. * @param x defines the x coordinate of the source
  3220. * @param y defines the y coordinate of the source
  3221. * @param z defines the z coordinate of the source
  3222. * @param result defines the Vector3 where to store the result
  3223. */
  3224. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3225. result.x = x;
  3226. result.y = y;
  3227. result.z = z;
  3228. };
  3229. /**
  3230. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3231. * @returns a new empty Vector3
  3232. */
  3233. Vector3.Zero = function () {
  3234. return new Vector3(0.0, 0.0, 0.0);
  3235. };
  3236. /**
  3237. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3238. * @returns a new unit Vector3
  3239. */
  3240. Vector3.One = function () {
  3241. return new Vector3(1.0, 1.0, 1.0);
  3242. };
  3243. /**
  3244. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3245. * @returns a new up Vector3
  3246. */
  3247. Vector3.Up = function () {
  3248. return new Vector3(0.0, 1.0, 0.0);
  3249. };
  3250. /**
  3251. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3252. * @returns a new forward Vector3
  3253. */
  3254. Vector3.Forward = function () {
  3255. return new Vector3(0.0, 0.0, 1.0);
  3256. };
  3257. /**
  3258. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3259. * @returns a new right Vector3
  3260. */
  3261. Vector3.Right = function () {
  3262. return new Vector3(1.0, 0.0, 0.0);
  3263. };
  3264. /**
  3265. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3266. * @returns a new left Vector3
  3267. */
  3268. Vector3.Left = function () {
  3269. return new Vector3(-1.0, 0.0, 0.0);
  3270. };
  3271. /**
  3272. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3273. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3274. * @param vector defines the Vector3 to transform
  3275. * @param transformation defines the transformation matrix
  3276. * @returns the transformed Vector3
  3277. */
  3278. Vector3.TransformCoordinates = function (vector, transformation) {
  3279. var result = Vector3.Zero();
  3280. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3281. return result;
  3282. };
  3283. /**
  3284. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3285. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3286. * @param vector defines the Vector3 to transform
  3287. * @param transformation defines the transformation matrix
  3288. * @param result defines the Vector3 where to store the result
  3289. */
  3290. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3291. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3292. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3293. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3294. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3295. result.x = x / w;
  3296. result.y = y / w;
  3297. result.z = z / w;
  3298. };
  3299. /**
  3300. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3301. * This method computes tranformed coordinates only, not transformed direction vectors
  3302. * @param x define the x coordinate of the source vector
  3303. * @param y define the y coordinate of the source vector
  3304. * @param z define the z coordinate of the source vector
  3305. * @param transformation defines the transformation matrix
  3306. * @param result defines the Vector3 where to store the result
  3307. */
  3308. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3309. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3310. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3311. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3312. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3313. result.x = rx / rw;
  3314. result.y = ry / rw;
  3315. result.z = rz / rw;
  3316. };
  3317. /**
  3318. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3319. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3320. * @param vector defines the Vector3 to transform
  3321. * @param transformation defines the transformation matrix
  3322. * @returns the new Vector3
  3323. */
  3324. Vector3.TransformNormal = function (vector, transformation) {
  3325. var result = Vector3.Zero();
  3326. Vector3.TransformNormalToRef(vector, transformation, result);
  3327. return result;
  3328. };
  3329. /**
  3330. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3331. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3332. * @param vector defines the Vector3 to transform
  3333. * @param transformation defines the transformation matrix
  3334. * @param result defines the Vector3 where to store the result
  3335. */
  3336. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3337. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3338. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3339. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3340. result.x = x;
  3341. result.y = y;
  3342. result.z = z;
  3343. };
  3344. /**
  3345. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3346. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3347. * @param x define the x coordinate of the source vector
  3348. * @param y define the y coordinate of the source vector
  3349. * @param z define the z coordinate of the source vector
  3350. * @param transformation defines the transformation matrix
  3351. * @param result defines the Vector3 where to store the result
  3352. */
  3353. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3354. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3355. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3356. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3357. };
  3358. /**
  3359. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3360. * @param value1 defines the first control point
  3361. * @param value2 defines the second control point
  3362. * @param value3 defines the third control point
  3363. * @param value4 defines the fourth control point
  3364. * @param amount defines the amount on the spline to use
  3365. * @returns the new Vector3
  3366. */
  3367. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3368. var squared = amount * amount;
  3369. var cubed = amount * squared;
  3370. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3371. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3372. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3373. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3374. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3375. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3376. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3377. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3378. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3379. return new Vector3(x, y, z);
  3380. };
  3381. /**
  3382. * 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"
  3383. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3384. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3385. * @param value defines the current value
  3386. * @param min defines the lower range value
  3387. * @param max defines the upper range value
  3388. * @returns the new Vector3
  3389. */
  3390. Vector3.Clamp = function (value, min, max) {
  3391. var x = value.x;
  3392. x = (x > max.x) ? max.x : x;
  3393. x = (x < min.x) ? min.x : x;
  3394. var y = value.y;
  3395. y = (y > max.y) ? max.y : y;
  3396. y = (y < min.y) ? min.y : y;
  3397. var z = value.z;
  3398. z = (z > max.z) ? max.z : z;
  3399. z = (z < min.z) ? min.z : z;
  3400. return new Vector3(x, y, z);
  3401. };
  3402. /**
  3403. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3404. * @param value1 defines the first control point
  3405. * @param tangent1 defines the first tangent vector
  3406. * @param value2 defines the second control point
  3407. * @param tangent2 defines the second tangent vector
  3408. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3409. * @returns the new Vector3
  3410. */
  3411. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3412. var squared = amount * amount;
  3413. var cubed = amount * squared;
  3414. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3415. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3416. var part3 = (cubed - (2.0 * squared)) + amount;
  3417. var part4 = cubed - squared;
  3418. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3419. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3420. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3421. return new Vector3(x, y, z);
  3422. };
  3423. /**
  3424. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3425. * @param start defines the start value
  3426. * @param end defines the end value
  3427. * @param amount max defines amount between both (between 0 and 1)
  3428. * @returns the new Vector3
  3429. */
  3430. Vector3.Lerp = function (start, end, amount) {
  3431. var result = new Vector3(0, 0, 0);
  3432. Vector3.LerpToRef(start, end, amount, result);
  3433. return result;
  3434. };
  3435. /**
  3436. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3437. * @param start defines the start value
  3438. * @param end defines the end value
  3439. * @param amount max defines amount between both (between 0 and 1)
  3440. * @param result defines the Vector3 where to store the result
  3441. */
  3442. Vector3.LerpToRef = function (start, end, amount, result) {
  3443. result.x = start.x + ((end.x - start.x) * amount);
  3444. result.y = start.y + ((end.y - start.y) * amount);
  3445. result.z = start.z + ((end.z - start.z) * amount);
  3446. };
  3447. /**
  3448. * Returns the dot product (float) between the vectors "left" and "right"
  3449. * @param left defines the left operand
  3450. * @param right defines the right operand
  3451. * @returns the dot product
  3452. */
  3453. Vector3.Dot = function (left, right) {
  3454. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3455. };
  3456. /**
  3457. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3458. * The cross product is then orthogonal to both "left" and "right"
  3459. * @param left defines the left operand
  3460. * @param right defines the right operand
  3461. * @returns the cross product
  3462. */
  3463. Vector3.Cross = function (left, right) {
  3464. var result = Vector3.Zero();
  3465. Vector3.CrossToRef(left, right, result);
  3466. return result;
  3467. };
  3468. /**
  3469. * Sets the passed vector "result" with the cross product of "left" and "right"
  3470. * The cross product is then orthogonal to both "left" and "right"
  3471. * @param left defines the left operand
  3472. * @param right defines the right operand
  3473. * @param result defines the Vector3 where to store the result
  3474. */
  3475. Vector3.CrossToRef = function (left, right, result) {
  3476. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3477. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3478. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3479. result.copyFrom(MathTmp.Vector3[0]);
  3480. };
  3481. /**
  3482. * Returns a new Vector3 as the normalization of the passed vector
  3483. * @param vector defines the Vector3 to normalize
  3484. * @returns the new Vector3
  3485. */
  3486. Vector3.Normalize = function (vector) {
  3487. var result = Vector3.Zero();
  3488. Vector3.NormalizeToRef(vector, result);
  3489. return result;
  3490. };
  3491. /**
  3492. * Sets the passed vector "result" with the normalization of the passed first vector
  3493. * @param vector defines the Vector3 to normalize
  3494. * @param result defines the Vector3 where to store the result
  3495. */
  3496. Vector3.NormalizeToRef = function (vector, result) {
  3497. result.copyFrom(vector);
  3498. result.normalize();
  3499. };
  3500. /**
  3501. * Project a Vector3 onto screen space
  3502. * @param vector defines the Vector3 to project
  3503. * @param world defines the world matrix to use
  3504. * @param transform defines the transform (view x projection) matrix to use
  3505. * @param viewport defines the screen viewport to use
  3506. * @returns the new Vector3
  3507. */
  3508. Vector3.Project = function (vector, world, transform, viewport) {
  3509. var cw = viewport.width;
  3510. var ch = viewport.height;
  3511. var cx = viewport.x;
  3512. var cy = viewport.y;
  3513. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3514. 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);
  3515. var matrix = MathTmp.Matrix[0];
  3516. world.multiplyToRef(transform, matrix);
  3517. matrix.multiplyToRef(viewportMatrix, matrix);
  3518. return Vector3.TransformCoordinates(vector, matrix);
  3519. };
  3520. /**
  3521. * Unproject from screen space to object space
  3522. * @param source defines the screen space Vector3 to use
  3523. * @param viewportWidth defines the current width of the viewport
  3524. * @param viewportHeight defines the current height of the viewport
  3525. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3526. * @param transform defines the transform (view x projection) matrix to use
  3527. * @returns the new Vector3
  3528. */
  3529. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3530. var matrix = MathTmp.Matrix[0];
  3531. world.multiplyToRef(transform, matrix);
  3532. matrix.invert();
  3533. source.x = source.x / viewportWidth * 2 - 1;
  3534. source.y = -(source.y / viewportHeight * 2 - 1);
  3535. var vector = Vector3.TransformCoordinates(source, matrix);
  3536. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3537. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3538. vector = vector.scale(1.0 / num);
  3539. }
  3540. return vector;
  3541. };
  3542. /**
  3543. * Unproject from screen space to object space
  3544. * @param source defines the screen space Vector3 to use
  3545. * @param viewportWidth defines the current width of the viewport
  3546. * @param viewportHeight defines the current height of the viewport
  3547. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3548. * @param view defines the view matrix to use
  3549. * @param projection defines the projection matrix to use
  3550. * @returns the new Vector3
  3551. */
  3552. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3553. var result = Vector3.Zero();
  3554. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3555. return result;
  3556. };
  3557. /**
  3558. * Unproject from screen space to object space
  3559. * @param source defines the screen space Vector3 to use
  3560. * @param viewportWidth defines the current width of the viewport
  3561. * @param viewportHeight defines the current height of the viewport
  3562. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3563. * @param view defines the view matrix to use
  3564. * @param projection defines the projection matrix to use
  3565. * @param result defines the Vector3 where to store the result
  3566. */
  3567. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3568. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3569. };
  3570. /**
  3571. * Unproject from screen space to object space
  3572. * @param sourceX defines the screen space x coordinate to use
  3573. * @param sourceY defines the screen space y coordinate to use
  3574. * @param sourceZ defines the screen space z coordinate to use
  3575. * @param viewportWidth defines the current width of the viewport
  3576. * @param viewportHeight defines the current height of the viewport
  3577. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3578. * @param view defines the view matrix to use
  3579. * @param projection defines the projection matrix to use
  3580. * @param result defines the Vector3 where to store the result
  3581. */
  3582. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3583. var matrix = MathTmp.Matrix[0];
  3584. world.multiplyToRef(view, matrix);
  3585. matrix.multiplyToRef(projection, matrix);
  3586. matrix.invert();
  3587. var screenSource = MathTmp.Vector3[0];
  3588. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3589. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3590. screenSource.z = 2 * sourceZ - 1.0;
  3591. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3592. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3593. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3594. result.scaleInPlace(1.0 / num);
  3595. }
  3596. };
  3597. /**
  3598. * Gets the minimal coordinate values between two Vector3
  3599. * @param left defines the first operand
  3600. * @param right defines the second operand
  3601. * @returns the new Vector3
  3602. */
  3603. Vector3.Minimize = function (left, right) {
  3604. var min = left.clone();
  3605. min.minimizeInPlace(right);
  3606. return min;
  3607. };
  3608. /**
  3609. * Gets the maximal coordinate values between two Vector3
  3610. * @param left defines the first operand
  3611. * @param right defines the second operand
  3612. * @returns the new Vector3
  3613. */
  3614. Vector3.Maximize = function (left, right) {
  3615. var max = left.clone();
  3616. max.maximizeInPlace(right);
  3617. return max;
  3618. };
  3619. /**
  3620. * Returns the distance between the vectors "value1" and "value2"
  3621. * @param value1 defines the first operand
  3622. * @param value2 defines the second operand
  3623. * @returns the distance
  3624. */
  3625. Vector3.Distance = function (value1, value2) {
  3626. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3627. };
  3628. /**
  3629. * Returns the squared distance between the vectors "value1" and "value2"
  3630. * @param value1 defines the first operand
  3631. * @param value2 defines the second operand
  3632. * @returns the squared distance
  3633. */
  3634. Vector3.DistanceSquared = function (value1, value2) {
  3635. var x = value1.x - value2.x;
  3636. var y = value1.y - value2.y;
  3637. var z = value1.z - value2.z;
  3638. return (x * x) + (y * y) + (z * z);
  3639. };
  3640. /**
  3641. * Returns a new Vector3 located at the center between "value1" and "value2"
  3642. * @param value1 defines the first operand
  3643. * @param value2 defines the second operand
  3644. * @returns the new Vector3
  3645. */
  3646. Vector3.Center = function (value1, value2) {
  3647. var center = value1.add(value2);
  3648. center.scaleInPlace(0.5);
  3649. return center;
  3650. };
  3651. /**
  3652. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3653. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3654. * to something in order to rotate it from its local system to the given target system
  3655. * Note: axis1, axis2 and axis3 are normalized during this operation
  3656. * @param axis1 defines the first axis
  3657. * @param axis2 defines the second axis
  3658. * @param axis3 defines the third axis
  3659. * @returns a new Vector3
  3660. */
  3661. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3662. var rotation = Vector3.Zero();
  3663. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3664. return rotation;
  3665. };
  3666. /**
  3667. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3668. * @param axis1 defines the first axis
  3669. * @param axis2 defines the second axis
  3670. * @param axis3 defines the third axis
  3671. * @param ref defines the Vector3 where to store the result
  3672. */
  3673. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3674. var quat = MathTmp.Quaternion[0];
  3675. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3676. quat.toEulerAnglesToRef(ref);
  3677. };
  3678. return Vector3;
  3679. }());
  3680. BABYLON.Vector3 = Vector3;
  3681. //Vector4 class created for EulerAngle class conversion to Quaternion
  3682. var Vector4 = /** @class */ (function () {
  3683. /**
  3684. * Creates a Vector4 object from the passed floats.
  3685. */
  3686. function Vector4(x, y, z, w) {
  3687. this.x = x;
  3688. this.y = y;
  3689. this.z = z;
  3690. this.w = w;
  3691. }
  3692. /**
  3693. * Returns the string with the Vector4 coordinates.
  3694. */
  3695. Vector4.prototype.toString = function () {
  3696. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3697. };
  3698. /**
  3699. * Returns the string "Vector4".
  3700. */
  3701. Vector4.prototype.getClassName = function () {
  3702. return "Vector4";
  3703. };
  3704. /**
  3705. * Returns the Vector4 hash code.
  3706. */
  3707. Vector4.prototype.getHashCode = function () {
  3708. var hash = this.x || 0;
  3709. hash = (hash * 397) ^ (this.y || 0);
  3710. hash = (hash * 397) ^ (this.z || 0);
  3711. hash = (hash * 397) ^ (this.w || 0);
  3712. return hash;
  3713. };
  3714. // Operators
  3715. /**
  3716. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3717. */
  3718. Vector4.prototype.asArray = function () {
  3719. var result = new Array();
  3720. this.toArray(result, 0);
  3721. return result;
  3722. };
  3723. /**
  3724. * Populates the passed array from the passed index with the Vector4 coordinates.
  3725. * Returns the Vector4.
  3726. */
  3727. Vector4.prototype.toArray = function (array, index) {
  3728. if (index === undefined) {
  3729. index = 0;
  3730. }
  3731. array[index] = this.x;
  3732. array[index + 1] = this.y;
  3733. array[index + 2] = this.z;
  3734. array[index + 3] = this.w;
  3735. return this;
  3736. };
  3737. /**
  3738. * Adds the passed vector to the current Vector4.
  3739. * Returns the updated Vector4.
  3740. */
  3741. Vector4.prototype.addInPlace = function (otherVector) {
  3742. this.x += otherVector.x;
  3743. this.y += otherVector.y;
  3744. this.z += otherVector.z;
  3745. this.w += otherVector.w;
  3746. return this;
  3747. };
  3748. /**
  3749. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3750. */
  3751. Vector4.prototype.add = function (otherVector) {
  3752. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3753. };
  3754. /**
  3755. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3756. * Returns the current Vector4.
  3757. */
  3758. Vector4.prototype.addToRef = function (otherVector, result) {
  3759. result.x = this.x + otherVector.x;
  3760. result.y = this.y + otherVector.y;
  3761. result.z = this.z + otherVector.z;
  3762. result.w = this.w + otherVector.w;
  3763. return this;
  3764. };
  3765. /**
  3766. * Subtract in place the passed vector from the current Vector4.
  3767. * Returns the updated Vector4.
  3768. */
  3769. Vector4.prototype.subtractInPlace = function (otherVector) {
  3770. this.x -= otherVector.x;
  3771. this.y -= otherVector.y;
  3772. this.z -= otherVector.z;
  3773. this.w -= otherVector.w;
  3774. return this;
  3775. };
  3776. /**
  3777. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3778. */
  3779. Vector4.prototype.subtract = function (otherVector) {
  3780. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3781. };
  3782. /**
  3783. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3784. * Returns the current Vector4.
  3785. */
  3786. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3787. result.x = this.x - otherVector.x;
  3788. result.y = this.y - otherVector.y;
  3789. result.z = this.z - otherVector.z;
  3790. result.w = this.w - otherVector.w;
  3791. return this;
  3792. };
  3793. /**
  3794. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3795. */
  3796. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3797. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3798. };
  3799. /**
  3800. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3801. * Returns the current Vector4.
  3802. */
  3803. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3804. result.x = this.x - x;
  3805. result.y = this.y - y;
  3806. result.z = this.z - z;
  3807. result.w = this.w - w;
  3808. return this;
  3809. };
  3810. /**
  3811. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3812. */
  3813. Vector4.prototype.negate = function () {
  3814. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3815. };
  3816. /**
  3817. * Multiplies the current Vector4 coordinates by scale (float).
  3818. * Returns the updated Vector4.
  3819. */
  3820. Vector4.prototype.scaleInPlace = function (scale) {
  3821. this.x *= scale;
  3822. this.y *= scale;
  3823. this.z *= scale;
  3824. this.w *= scale;
  3825. return this;
  3826. };
  3827. /**
  3828. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3829. */
  3830. Vector4.prototype.scale = function (scale) {
  3831. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3832. };
  3833. /**
  3834. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3835. * Returns the current Vector4.
  3836. */
  3837. Vector4.prototype.scaleToRef = function (scale, result) {
  3838. result.x = this.x * scale;
  3839. result.y = this.y * scale;
  3840. result.z = this.z * scale;
  3841. result.w = this.w * scale;
  3842. return this;
  3843. };
  3844. /**
  3845. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3846. * @param scale defines the scale factor
  3847. * @param result defines the Vector4 object where to store the result
  3848. * @returns the unmodified current Vector4
  3849. */
  3850. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3851. result.x += this.x * scale;
  3852. result.y += this.y * scale;
  3853. result.z += this.z * scale;
  3854. result.w += this.w * scale;
  3855. return this;
  3856. };
  3857. /**
  3858. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3859. */
  3860. Vector4.prototype.equals = function (otherVector) {
  3861. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3862. };
  3863. /**
  3864. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3865. */
  3866. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3867. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3868. return otherVector
  3869. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3870. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3871. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3872. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3873. };
  3874. /**
  3875. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3876. */
  3877. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3878. return this.x === x && this.y === y && this.z === z && this.w === w;
  3879. };
  3880. /**
  3881. * Multiplies in place the current Vector4 by the passed one.
  3882. * Returns the updated Vector4.
  3883. */
  3884. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3885. this.x *= otherVector.x;
  3886. this.y *= otherVector.y;
  3887. this.z *= otherVector.z;
  3888. this.w *= otherVector.w;
  3889. return this;
  3890. };
  3891. /**
  3892. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3893. */
  3894. Vector4.prototype.multiply = function (otherVector) {
  3895. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3896. };
  3897. /**
  3898. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3899. * Returns the current Vector4.
  3900. */
  3901. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3902. result.x = this.x * otherVector.x;
  3903. result.y = this.y * otherVector.y;
  3904. result.z = this.z * otherVector.z;
  3905. result.w = this.w * otherVector.w;
  3906. return this;
  3907. };
  3908. /**
  3909. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3910. */
  3911. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3912. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3913. };
  3914. /**
  3915. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3916. */
  3917. Vector4.prototype.divide = function (otherVector) {
  3918. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3919. };
  3920. /**
  3921. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3922. * Returns the current Vector4.
  3923. */
  3924. Vector4.prototype.divideToRef = function (otherVector, result) {
  3925. result.x = this.x / otherVector.x;
  3926. result.y = this.y / otherVector.y;
  3927. result.z = this.z / otherVector.z;
  3928. result.w = this.w / otherVector.w;
  3929. return this;
  3930. };
  3931. /**
  3932. * Divides the current Vector3 coordinates by the passed ones.
  3933. * @returns the updated Vector3.
  3934. */
  3935. Vector4.prototype.divideInPlace = function (otherVector) {
  3936. return this.divideToRef(otherVector, this);
  3937. };
  3938. /**
  3939. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3940. * @param other defines the second operand
  3941. * @returns the current updated Vector4
  3942. */
  3943. Vector4.prototype.minimizeInPlace = function (other) {
  3944. if (other.x < this.x)
  3945. this.x = other.x;
  3946. if (other.y < this.y)
  3947. this.y = other.y;
  3948. if (other.z < this.z)
  3949. this.z = other.z;
  3950. if (other.w < this.w)
  3951. this.w = other.w;
  3952. return this;
  3953. };
  3954. /**
  3955. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3956. * @param other defines the second operand
  3957. * @returns the current updated Vector4
  3958. */
  3959. Vector4.prototype.maximizeInPlace = function (other) {
  3960. if (other.x > this.x)
  3961. this.x = other.x;
  3962. if (other.y > this.y)
  3963. this.y = other.y;
  3964. if (other.z > this.z)
  3965. this.z = other.z;
  3966. if (other.w > this.w)
  3967. this.w = other.w;
  3968. return this;
  3969. };
  3970. // Properties
  3971. /**
  3972. * Returns the Vector4 length (float).
  3973. */
  3974. Vector4.prototype.length = function () {
  3975. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3976. };
  3977. /**
  3978. * Returns the Vector4 squared length (float).
  3979. */
  3980. Vector4.prototype.lengthSquared = function () {
  3981. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3982. };
  3983. // Methods
  3984. /**
  3985. * Normalizes in place the Vector4.
  3986. * Returns the updated Vector4.
  3987. */
  3988. Vector4.prototype.normalize = function () {
  3989. var len = this.length();
  3990. if (len === 0)
  3991. return this;
  3992. var num = 1.0 / len;
  3993. this.x *= num;
  3994. this.y *= num;
  3995. this.z *= num;
  3996. this.w *= num;
  3997. return this;
  3998. };
  3999. /**
  4000. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4001. */
  4002. Vector4.prototype.toVector3 = function () {
  4003. return new Vector3(this.x, this.y, this.z);
  4004. };
  4005. /**
  4006. * Returns a new Vector4 copied from the current one.
  4007. */
  4008. Vector4.prototype.clone = function () {
  4009. return new Vector4(this.x, this.y, this.z, this.w);
  4010. };
  4011. /**
  4012. * Updates the current Vector4 with the passed one coordinates.
  4013. * Returns the updated Vector4.
  4014. */
  4015. Vector4.prototype.copyFrom = function (source) {
  4016. this.x = source.x;
  4017. this.y = source.y;
  4018. this.z = source.z;
  4019. this.w = source.w;
  4020. return this;
  4021. };
  4022. /**
  4023. * Updates the current Vector4 coordinates with the passed floats.
  4024. * Returns the updated Vector4.
  4025. */
  4026. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4027. this.x = x;
  4028. this.y = y;
  4029. this.z = z;
  4030. this.w = w;
  4031. return this;
  4032. };
  4033. /**
  4034. * Updates the current Vector4 coordinates with the passed floats.
  4035. * Returns the updated Vector4.
  4036. */
  4037. Vector4.prototype.set = function (x, y, z, w) {
  4038. return this.copyFromFloats(x, y, z, w);
  4039. };
  4040. // Statics
  4041. /**
  4042. * Returns a new Vector4 set from the starting index of the passed array.
  4043. */
  4044. Vector4.FromArray = function (array, offset) {
  4045. if (!offset) {
  4046. offset = 0;
  4047. }
  4048. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4049. };
  4050. /**
  4051. * Updates the passed vector "result" from the starting index of the passed array.
  4052. */
  4053. Vector4.FromArrayToRef = function (array, offset, result) {
  4054. result.x = array[offset];
  4055. result.y = array[offset + 1];
  4056. result.z = array[offset + 2];
  4057. result.w = array[offset + 3];
  4058. };
  4059. /**
  4060. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  4061. */
  4062. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4063. Vector4.FromArrayToRef(array, offset, result);
  4064. };
  4065. /**
  4066. * Updates the passed vector "result" coordinates from the passed floats.
  4067. */
  4068. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4069. result.x = x;
  4070. result.y = y;
  4071. result.z = z;
  4072. result.w = w;
  4073. };
  4074. /**
  4075. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4076. */
  4077. Vector4.Zero = function () {
  4078. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4079. };
  4080. /**
  4081. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4082. */
  4083. Vector4.One = function () {
  4084. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4085. };
  4086. /**
  4087. * Returns a new normalized Vector4 from the passed one.
  4088. */
  4089. Vector4.Normalize = function (vector) {
  4090. var result = Vector4.Zero();
  4091. Vector4.NormalizeToRef(vector, result);
  4092. return result;
  4093. };
  4094. /**
  4095. * Updates the passed vector "result" from the normalization of the passed one.
  4096. */
  4097. Vector4.NormalizeToRef = function (vector, result) {
  4098. result.copyFrom(vector);
  4099. result.normalize();
  4100. };
  4101. Vector4.Minimize = function (left, right) {
  4102. var min = left.clone();
  4103. min.minimizeInPlace(right);
  4104. return min;
  4105. };
  4106. Vector4.Maximize = function (left, right) {
  4107. var max = left.clone();
  4108. max.maximizeInPlace(right);
  4109. return max;
  4110. };
  4111. /**
  4112. * Returns the distance (float) between the vectors "value1" and "value2".
  4113. */
  4114. Vector4.Distance = function (value1, value2) {
  4115. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4116. };
  4117. /**
  4118. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4119. */
  4120. Vector4.DistanceSquared = function (value1, value2) {
  4121. var x = value1.x - value2.x;
  4122. var y = value1.y - value2.y;
  4123. var z = value1.z - value2.z;
  4124. var w = value1.w - value2.w;
  4125. return (x * x) + (y * y) + (z * z) + (w * w);
  4126. };
  4127. /**
  4128. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4129. */
  4130. Vector4.Center = function (value1, value2) {
  4131. var center = value1.add(value2);
  4132. center.scaleInPlace(0.5);
  4133. return center;
  4134. };
  4135. /**
  4136. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4137. * This methods computes transformed normalized direction vectors only.
  4138. */
  4139. Vector4.TransformNormal = function (vector, transformation) {
  4140. var result = Vector4.Zero();
  4141. Vector4.TransformNormalToRef(vector, transformation, result);
  4142. return result;
  4143. };
  4144. /**
  4145. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4146. * This methods computes transformed normalized direction vectors only.
  4147. */
  4148. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4149. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4150. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4151. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4152. result.x = x;
  4153. result.y = y;
  4154. result.z = z;
  4155. result.w = vector.w;
  4156. };
  4157. /**
  4158. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4159. * This methods computes transformed normalized direction vectors only.
  4160. */
  4161. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4162. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4163. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4164. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4165. result.w = w;
  4166. };
  4167. return Vector4;
  4168. }());
  4169. BABYLON.Vector4 = Vector4;
  4170. var Size = /** @class */ (function () {
  4171. /**
  4172. * Creates a Size object from the passed width and height (floats).
  4173. */
  4174. function Size(width, height) {
  4175. this.width = width;
  4176. this.height = height;
  4177. }
  4178. // Returns a string with the Size width and height.
  4179. Size.prototype.toString = function () {
  4180. return "{W: " + this.width + ", H: " + this.height + "}";
  4181. };
  4182. /**
  4183. * Returns the string "Size"
  4184. */
  4185. Size.prototype.getClassName = function () {
  4186. return "Size";
  4187. };
  4188. /**
  4189. * Returns the Size hash code.
  4190. */
  4191. Size.prototype.getHashCode = function () {
  4192. var hash = this.width || 0;
  4193. hash = (hash * 397) ^ (this.height || 0);
  4194. return hash;
  4195. };
  4196. /**
  4197. * Updates the current size from the passed one.
  4198. * Returns the updated Size.
  4199. */
  4200. Size.prototype.copyFrom = function (src) {
  4201. this.width = src.width;
  4202. this.height = src.height;
  4203. };
  4204. /**
  4205. * Updates in place the current Size from the passed floats.
  4206. * Returns the updated Size.
  4207. */
  4208. Size.prototype.copyFromFloats = function (width, height) {
  4209. this.width = width;
  4210. this.height = height;
  4211. return this;
  4212. };
  4213. /**
  4214. * Updates in place the current Size from the passed floats.
  4215. * Returns the updated Size.
  4216. */
  4217. Size.prototype.set = function (width, height) {
  4218. return this.copyFromFloats(width, height);
  4219. };
  4220. /**
  4221. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4222. */
  4223. Size.prototype.multiplyByFloats = function (w, h) {
  4224. return new Size(this.width * w, this.height * h);
  4225. };
  4226. /**
  4227. * Returns a new Size copied from the passed one.
  4228. */
  4229. Size.prototype.clone = function () {
  4230. return new Size(this.width, this.height);
  4231. };
  4232. /**
  4233. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4234. */
  4235. Size.prototype.equals = function (other) {
  4236. if (!other) {
  4237. return false;
  4238. }
  4239. return (this.width === other.width) && (this.height === other.height);
  4240. };
  4241. Object.defineProperty(Size.prototype, "surface", {
  4242. /**
  4243. * Returns the surface of the Size : width * height (float).
  4244. */
  4245. get: function () {
  4246. return this.width * this.height;
  4247. },
  4248. enumerable: true,
  4249. configurable: true
  4250. });
  4251. /**
  4252. * Returns a new Size set to (0.0, 0.0)
  4253. */
  4254. Size.Zero = function () {
  4255. return new Size(0.0, 0.0);
  4256. };
  4257. /**
  4258. * Returns a new Size set as the addition result of the current Size and the passed one.
  4259. */
  4260. Size.prototype.add = function (otherSize) {
  4261. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4262. return r;
  4263. };
  4264. /**
  4265. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4266. */
  4267. Size.prototype.subtract = function (otherSize) {
  4268. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4269. return r;
  4270. };
  4271. /**
  4272. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4273. */
  4274. Size.Lerp = function (start, end, amount) {
  4275. var w = start.width + ((end.width - start.width) * amount);
  4276. var h = start.height + ((end.height - start.height) * amount);
  4277. return new Size(w, h);
  4278. };
  4279. return Size;
  4280. }());
  4281. BABYLON.Size = Size;
  4282. var Quaternion = /** @class */ (function () {
  4283. /**
  4284. * Creates a new Quaternion from the passed floats.
  4285. */
  4286. function Quaternion(x, y, z, w) {
  4287. if (x === void 0) { x = 0.0; }
  4288. if (y === void 0) { y = 0.0; }
  4289. if (z === void 0) { z = 0.0; }
  4290. if (w === void 0) { w = 1.0; }
  4291. this.x = x;
  4292. this.y = y;
  4293. this.z = z;
  4294. this.w = w;
  4295. }
  4296. /**
  4297. * Returns a string with the Quaternion coordinates.
  4298. */
  4299. Quaternion.prototype.toString = function () {
  4300. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4301. };
  4302. /**
  4303. * Returns the string "Quaternion".
  4304. */
  4305. Quaternion.prototype.getClassName = function () {
  4306. return "Quaternion";
  4307. };
  4308. /**
  4309. * Returns the Quaternion hash code.
  4310. */
  4311. Quaternion.prototype.getHashCode = function () {
  4312. var hash = this.x || 0;
  4313. hash = (hash * 397) ^ (this.y || 0);
  4314. hash = (hash * 397) ^ (this.z || 0);
  4315. hash = (hash * 397) ^ (this.w || 0);
  4316. return hash;
  4317. };
  4318. /**
  4319. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4320. */
  4321. Quaternion.prototype.asArray = function () {
  4322. return [this.x, this.y, this.z, this.w];
  4323. };
  4324. /**
  4325. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4326. */
  4327. Quaternion.prototype.equals = function (otherQuaternion) {
  4328. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4329. };
  4330. /**
  4331. * Returns a new Quaternion copied from the current one.
  4332. */
  4333. Quaternion.prototype.clone = function () {
  4334. return new Quaternion(this.x, this.y, this.z, this.w);
  4335. };
  4336. /**
  4337. * Updates the current Quaternion from the passed one coordinates.
  4338. * Returns the updated Quaterion.
  4339. */
  4340. Quaternion.prototype.copyFrom = function (other) {
  4341. this.x = other.x;
  4342. this.y = other.y;
  4343. this.z = other.z;
  4344. this.w = other.w;
  4345. return this;
  4346. };
  4347. /**
  4348. * Updates the current Quaternion from the passed float coordinates.
  4349. * Returns the updated Quaterion.
  4350. */
  4351. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4352. this.x = x;
  4353. this.y = y;
  4354. this.z = z;
  4355. this.w = w;
  4356. return this;
  4357. };
  4358. /**
  4359. * Updates the current Quaternion from the passed float coordinates.
  4360. * Returns the updated Quaterion.
  4361. */
  4362. Quaternion.prototype.set = function (x, y, z, w) {
  4363. return this.copyFromFloats(x, y, z, w);
  4364. };
  4365. /**
  4366. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4367. */
  4368. Quaternion.prototype.add = function (other) {
  4369. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4370. };
  4371. /**
  4372. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4373. */
  4374. Quaternion.prototype.subtract = function (other) {
  4375. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4376. };
  4377. /**
  4378. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4379. */
  4380. Quaternion.prototype.scale = function (value) {
  4381. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4382. };
  4383. /**
  4384. * Scale the current Quaternion values by a factor to a given Quaternion
  4385. * @param scale defines the scale factor
  4386. * @param result defines the Quaternion object where to store the result
  4387. * @returns the unmodified current Quaternion
  4388. */
  4389. Quaternion.prototype.scaleToRef = function (scale, result) {
  4390. result.x = this.x * scale;
  4391. result.y = this.y * scale;
  4392. result.z = this.z * scale;
  4393. result.w = this.w * scale;
  4394. return this;
  4395. };
  4396. /**
  4397. * Scale the current Quaternion values by a factor and add the result to a given Quaternion
  4398. * @param scale defines the scale factor
  4399. * @param result defines the Quaternion object where to store the result
  4400. * @returns the unmodified current Quaternion
  4401. */
  4402. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4403. result.x += this.x * scale;
  4404. result.y += this.y * scale;
  4405. result.z += this.z * scale;
  4406. result.w += this.w * scale;
  4407. return this;
  4408. };
  4409. /**
  4410. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4411. */
  4412. Quaternion.prototype.multiply = function (q1) {
  4413. var result = new Quaternion(0, 0, 0, 1.0);
  4414. this.multiplyToRef(q1, result);
  4415. return result;
  4416. };
  4417. /**
  4418. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4419. * Returns the current Quaternion.
  4420. */
  4421. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4422. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4423. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4424. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4425. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4426. result.copyFromFloats(x, y, z, w);
  4427. return this;
  4428. };
  4429. /**
  4430. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4431. * Returns the updated Quaternion.
  4432. */
  4433. Quaternion.prototype.multiplyInPlace = function (q1) {
  4434. this.multiplyToRef(q1, this);
  4435. return this;
  4436. };
  4437. /**
  4438. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4439. * Returns the current Quaternion.
  4440. */
  4441. Quaternion.prototype.conjugateToRef = function (ref) {
  4442. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4443. return this;
  4444. };
  4445. /**
  4446. * Conjugates in place the current Quaternion.
  4447. * Returns the updated Quaternion.
  4448. */
  4449. Quaternion.prototype.conjugateInPlace = function () {
  4450. this.x *= -1;
  4451. this.y *= -1;
  4452. this.z *= -1;
  4453. return this;
  4454. };
  4455. /**
  4456. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4457. */
  4458. Quaternion.prototype.conjugate = function () {
  4459. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4460. return result;
  4461. };
  4462. /**
  4463. * Returns the Quaternion length (float).
  4464. */
  4465. Quaternion.prototype.length = function () {
  4466. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4467. };
  4468. /**
  4469. * Normalize in place the current Quaternion.
  4470. * Returns the updated Quaternion.
  4471. */
  4472. Quaternion.prototype.normalize = function () {
  4473. var length = 1.0 / this.length();
  4474. this.x *= length;
  4475. this.y *= length;
  4476. this.z *= length;
  4477. this.w *= length;
  4478. return this;
  4479. };
  4480. /**
  4481. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion
  4482. * @param order is a reserved parameter and is ignore for now
  4483. * @returns the new Vector3
  4484. */
  4485. Quaternion.prototype.toEulerAngles = function (order) {
  4486. if (order === void 0) { order = "YZX"; }
  4487. var result = Vector3.Zero();
  4488. this.toEulerAnglesToRef(result, order);
  4489. return result;
  4490. };
  4491. /**
  4492. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion
  4493. * @param result defines the vector which will be filled with the Euler angles
  4494. * @param order is a reserved parameter and is ignore for now
  4495. * @returns the current Quaternion
  4496. */
  4497. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4498. if (order === void 0) { order = "YZX"; }
  4499. var qz = this.z;
  4500. var qx = this.x;
  4501. var qy = this.y;
  4502. var qw = this.w;
  4503. var sqw = qw * qw;
  4504. var sqz = qz * qz;
  4505. var sqx = qx * qx;
  4506. var sqy = qy * qy;
  4507. var zAxisY = qy * qz - qx * qw;
  4508. var limit = .4999999;
  4509. if (zAxisY < -limit) {
  4510. result.y = 2 * Math.atan2(qy, qw);
  4511. result.x = Math.PI / 2;
  4512. result.z = 0;
  4513. }
  4514. else if (zAxisY > limit) {
  4515. result.y = 2 * Math.atan2(qy, qw);
  4516. result.x = -Math.PI / 2;
  4517. result.z = 0;
  4518. }
  4519. else {
  4520. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4521. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4522. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4523. }
  4524. return this;
  4525. };
  4526. /**
  4527. * Updates the passed rotation matrix with the current Quaternion values.
  4528. * Returns the current Quaternion.
  4529. */
  4530. Quaternion.prototype.toRotationMatrix = function (result) {
  4531. var xx = this.x * this.x;
  4532. var yy = this.y * this.y;
  4533. var zz = this.z * this.z;
  4534. var xy = this.x * this.y;
  4535. var zw = this.z * this.w;
  4536. var zx = this.z * this.x;
  4537. var yw = this.y * this.w;
  4538. var yz = this.y * this.z;
  4539. var xw = this.x * this.w;
  4540. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4541. result.m[1] = 2.0 * (xy + zw);
  4542. result.m[2] = 2.0 * (zx - yw);
  4543. result.m[3] = 0;
  4544. result.m[4] = 2.0 * (xy - zw);
  4545. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4546. result.m[6] = 2.0 * (yz + xw);
  4547. result.m[7] = 0;
  4548. result.m[8] = 2.0 * (zx + yw);
  4549. result.m[9] = 2.0 * (yz - xw);
  4550. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4551. result.m[11] = 0;
  4552. result.m[12] = 0;
  4553. result.m[13] = 0;
  4554. result.m[14] = 0;
  4555. result.m[15] = 1.0;
  4556. result._markAsUpdated();
  4557. return this;
  4558. };
  4559. /**
  4560. * Updates the current Quaternion from the passed rotation matrix values.
  4561. * Returns the updated Quaternion.
  4562. */
  4563. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4564. Quaternion.FromRotationMatrixToRef(matrix, this);
  4565. return this;
  4566. };
  4567. // Statics
  4568. /**
  4569. * Returns a new Quaternion set from the passed rotation matrix values.
  4570. */
  4571. Quaternion.FromRotationMatrix = function (matrix) {
  4572. var result = new Quaternion();
  4573. Quaternion.FromRotationMatrixToRef(matrix, result);
  4574. return result;
  4575. };
  4576. /**
  4577. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4578. */
  4579. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4580. var data = matrix.m;
  4581. var m11 = data[0], m12 = data[4], m13 = data[8];
  4582. var m21 = data[1], m22 = data[5], m23 = data[9];
  4583. var m31 = data[2], m32 = data[6], m33 = data[10];
  4584. var trace = m11 + m22 + m33;
  4585. var s;
  4586. if (trace > 0) {
  4587. s = 0.5 / Math.sqrt(trace + 1.0);
  4588. result.w = 0.25 / s;
  4589. result.x = (m32 - m23) * s;
  4590. result.y = (m13 - m31) * s;
  4591. result.z = (m21 - m12) * s;
  4592. }
  4593. else if (m11 > m22 && m11 > m33) {
  4594. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4595. result.w = (m32 - m23) / s;
  4596. result.x = 0.25 * s;
  4597. result.y = (m12 + m21) / s;
  4598. result.z = (m13 + m31) / s;
  4599. }
  4600. else if (m22 > m33) {
  4601. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4602. result.w = (m13 - m31) / s;
  4603. result.x = (m12 + m21) / s;
  4604. result.y = 0.25 * s;
  4605. result.z = (m23 + m32) / s;
  4606. }
  4607. else {
  4608. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4609. result.w = (m21 - m12) / s;
  4610. result.x = (m13 + m31) / s;
  4611. result.y = (m23 + m32) / s;
  4612. result.z = 0.25 * s;
  4613. }
  4614. };
  4615. /**
  4616. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4617. */
  4618. Quaternion.Zero = function () {
  4619. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4620. };
  4621. /**
  4622. * Returns a new Quaternion as the inverted current Quaternion.
  4623. */
  4624. Quaternion.Inverse = function (q) {
  4625. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4626. };
  4627. /**
  4628. * Returns the identity Quaternion.
  4629. */
  4630. Quaternion.Identity = function () {
  4631. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4632. };
  4633. Quaternion.IsIdentity = function (quaternion) {
  4634. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4635. };
  4636. /**
  4637. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4638. */
  4639. Quaternion.RotationAxis = function (axis, angle) {
  4640. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4641. };
  4642. /**
  4643. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4644. */
  4645. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4646. var sin = Math.sin(angle / 2);
  4647. axis.normalize();
  4648. result.w = Math.cos(angle / 2);
  4649. result.x = axis.x * sin;
  4650. result.y = axis.y * sin;
  4651. result.z = axis.z * sin;
  4652. return result;
  4653. };
  4654. /**
  4655. * Retuns a new Quaternion set from the starting index of the passed array.
  4656. */
  4657. Quaternion.FromArray = function (array, offset) {
  4658. if (!offset) {
  4659. offset = 0;
  4660. }
  4661. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4662. };
  4663. /**
  4664. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4665. */
  4666. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4667. var q = new Quaternion();
  4668. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4669. return q;
  4670. };
  4671. /**
  4672. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4673. */
  4674. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4675. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4676. var halfRoll = roll * 0.5;
  4677. var halfPitch = pitch * 0.5;
  4678. var halfYaw = yaw * 0.5;
  4679. var sinRoll = Math.sin(halfRoll);
  4680. var cosRoll = Math.cos(halfRoll);
  4681. var sinPitch = Math.sin(halfPitch);
  4682. var cosPitch = Math.cos(halfPitch);
  4683. var sinYaw = Math.sin(halfYaw);
  4684. var cosYaw = Math.cos(halfYaw);
  4685. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4686. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4687. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4688. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4689. };
  4690. /**
  4691. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4692. */
  4693. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4694. var result = new Quaternion();
  4695. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4696. return result;
  4697. };
  4698. /**
  4699. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4700. */
  4701. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4702. // Produces a quaternion from Euler angles in the z-x-z orientation
  4703. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4704. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4705. var halfBeta = beta * 0.5;
  4706. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4707. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4708. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4709. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4710. };
  4711. /**
  4712. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4713. * cf to Vector3.RotationFromAxis() documentation.
  4714. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4715. */
  4716. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4717. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4718. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4719. return quat;
  4720. };
  4721. /**
  4722. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4723. * cf to Vector3.RotationFromAxis() documentation.
  4724. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4725. */
  4726. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4727. var rotMat = MathTmp.Matrix[0];
  4728. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4729. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4730. };
  4731. Quaternion.Slerp = function (left, right, amount) {
  4732. var result = Quaternion.Identity();
  4733. Quaternion.SlerpToRef(left, right, amount, result);
  4734. return result;
  4735. };
  4736. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4737. var num2;
  4738. var num3;
  4739. var num = amount;
  4740. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4741. var flag = false;
  4742. if (num4 < 0) {
  4743. flag = true;
  4744. num4 = -num4;
  4745. }
  4746. if (num4 > 0.999999) {
  4747. num3 = 1 - num;
  4748. num2 = flag ? -num : num;
  4749. }
  4750. else {
  4751. var num5 = Math.acos(num4);
  4752. var num6 = (1.0 / Math.sin(num5));
  4753. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4754. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4755. }
  4756. result.x = (num3 * left.x) + (num2 * right.x);
  4757. result.y = (num3 * left.y) + (num2 * right.y);
  4758. result.z = (num3 * left.z) + (num2 * right.z);
  4759. result.w = (num3 * left.w) + (num2 * right.w);
  4760. };
  4761. /**
  4762. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4763. */
  4764. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4765. var squared = amount * amount;
  4766. var cubed = amount * squared;
  4767. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4768. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4769. var part3 = (cubed - (2.0 * squared)) + amount;
  4770. var part4 = cubed - squared;
  4771. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4772. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4773. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4774. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4775. return new Quaternion(x, y, z, w);
  4776. };
  4777. return Quaternion;
  4778. }());
  4779. BABYLON.Quaternion = Quaternion;
  4780. var Matrix = /** @class */ (function () {
  4781. function Matrix() {
  4782. this._isIdentity = false;
  4783. this._isIdentityDirty = true;
  4784. this.m = new Float32Array(16);
  4785. this._markAsUpdated();
  4786. }
  4787. Matrix.prototype._markAsUpdated = function () {
  4788. this.updateFlag = Matrix._updateFlagSeed++;
  4789. this._isIdentityDirty = true;
  4790. };
  4791. // Properties
  4792. /**
  4793. * Boolean : True is the matrix is the identity matrix
  4794. */
  4795. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4796. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4797. if (this._isIdentityDirty) {
  4798. this._isIdentityDirty = false;
  4799. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4800. this._isIdentity = false;
  4801. }
  4802. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4803. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4804. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4805. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4806. this._isIdentity = false;
  4807. }
  4808. else {
  4809. this._isIdentity = true;
  4810. }
  4811. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4812. this._isIdentity = false;
  4813. }
  4814. }
  4815. return this._isIdentity;
  4816. };
  4817. /**
  4818. * Returns the matrix determinant (float).
  4819. */
  4820. Matrix.prototype.determinant = function () {
  4821. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4822. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4823. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4824. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4825. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4826. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4827. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4828. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4829. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4830. };
  4831. // Methods
  4832. /**
  4833. * Returns the matrix underlying array.
  4834. */
  4835. Matrix.prototype.toArray = function () {
  4836. return this.m;
  4837. };
  4838. /**
  4839. * Returns the matrix underlying array.
  4840. */
  4841. Matrix.prototype.asArray = function () {
  4842. return this.toArray();
  4843. };
  4844. /**
  4845. * Inverts in place the Matrix.
  4846. * Returns the Matrix inverted.
  4847. */
  4848. Matrix.prototype.invert = function () {
  4849. this.invertToRef(this);
  4850. return this;
  4851. };
  4852. /**
  4853. * Sets all the matrix elements to zero.
  4854. * Returns the Matrix.
  4855. */
  4856. Matrix.prototype.reset = function () {
  4857. for (var index = 0; index < 16; index++) {
  4858. this.m[index] = 0.0;
  4859. }
  4860. this._markAsUpdated();
  4861. return this;
  4862. };
  4863. /**
  4864. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4865. */
  4866. Matrix.prototype.add = function (other) {
  4867. var result = new Matrix();
  4868. this.addToRef(other, result);
  4869. return result;
  4870. };
  4871. /**
  4872. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4873. * Returns the Matrix.
  4874. */
  4875. Matrix.prototype.addToRef = function (other, result) {
  4876. for (var index = 0; index < 16; index++) {
  4877. result.m[index] = this.m[index] + other.m[index];
  4878. }
  4879. result._markAsUpdated();
  4880. return this;
  4881. };
  4882. /**
  4883. * Adds in place the passed matrix to the current Matrix.
  4884. * Returns the updated Matrix.
  4885. */
  4886. Matrix.prototype.addToSelf = function (other) {
  4887. for (var index = 0; index < 16; index++) {
  4888. this.m[index] += other.m[index];
  4889. }
  4890. this._markAsUpdated();
  4891. return this;
  4892. };
  4893. /**
  4894. * Sets the passed matrix with the current inverted Matrix.
  4895. * Returns the unmodified current Matrix.
  4896. */
  4897. Matrix.prototype.invertToRef = function (other) {
  4898. var l1 = this.m[0];
  4899. var l2 = this.m[1];
  4900. var l3 = this.m[2];
  4901. var l4 = this.m[3];
  4902. var l5 = this.m[4];
  4903. var l6 = this.m[5];
  4904. var l7 = this.m[6];
  4905. var l8 = this.m[7];
  4906. var l9 = this.m[8];
  4907. var l10 = this.m[9];
  4908. var l11 = this.m[10];
  4909. var l12 = this.m[11];
  4910. var l13 = this.m[12];
  4911. var l14 = this.m[13];
  4912. var l15 = this.m[14];
  4913. var l16 = this.m[15];
  4914. var l17 = (l11 * l16) - (l12 * l15);
  4915. var l18 = (l10 * l16) - (l12 * l14);
  4916. var l19 = (l10 * l15) - (l11 * l14);
  4917. var l20 = (l9 * l16) - (l12 * l13);
  4918. var l21 = (l9 * l15) - (l11 * l13);
  4919. var l22 = (l9 * l14) - (l10 * l13);
  4920. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4921. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4922. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4923. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4924. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4925. var l28 = (l7 * l16) - (l8 * l15);
  4926. var l29 = (l6 * l16) - (l8 * l14);
  4927. var l30 = (l6 * l15) - (l7 * l14);
  4928. var l31 = (l5 * l16) - (l8 * l13);
  4929. var l32 = (l5 * l15) - (l7 * l13);
  4930. var l33 = (l5 * l14) - (l6 * l13);
  4931. var l34 = (l7 * l12) - (l8 * l11);
  4932. var l35 = (l6 * l12) - (l8 * l10);
  4933. var l36 = (l6 * l11) - (l7 * l10);
  4934. var l37 = (l5 * l12) - (l8 * l9);
  4935. var l38 = (l5 * l11) - (l7 * l9);
  4936. var l39 = (l5 * l10) - (l6 * l9);
  4937. other.m[0] = l23 * l27;
  4938. other.m[4] = l24 * l27;
  4939. other.m[8] = l25 * l27;
  4940. other.m[12] = l26 * l27;
  4941. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4942. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4943. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4944. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4945. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4946. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4947. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4948. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4949. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4950. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4951. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4952. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4953. other._markAsUpdated();
  4954. return this;
  4955. };
  4956. /**
  4957. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4958. * Returns the updated Matrix.
  4959. */
  4960. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4961. this.m[12] = x;
  4962. this.m[13] = y;
  4963. this.m[14] = z;
  4964. this._markAsUpdated();
  4965. return this;
  4966. };
  4967. /**
  4968. * Inserts the translation vector in the current Matrix.
  4969. * Returns the updated Matrix.
  4970. */
  4971. Matrix.prototype.setTranslation = function (vector3) {
  4972. this.m[12] = vector3.x;
  4973. this.m[13] = vector3.y;
  4974. this.m[14] = vector3.z;
  4975. this._markAsUpdated();
  4976. return this;
  4977. };
  4978. /**
  4979. * Returns a new Vector3 as the extracted translation from the Matrix.
  4980. */
  4981. Matrix.prototype.getTranslation = function () {
  4982. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4983. };
  4984. /**
  4985. * Fill a Vector3 with the extracted translation from the Matrix.
  4986. */
  4987. Matrix.prototype.getTranslationToRef = function (result) {
  4988. result.x = this.m[12];
  4989. result.y = this.m[13];
  4990. result.z = this.m[14];
  4991. return this;
  4992. };
  4993. /**
  4994. * Remove rotation and scaling part from the Matrix.
  4995. * Returns the updated Matrix.
  4996. */
  4997. Matrix.prototype.removeRotationAndScaling = function () {
  4998. this.setRowFromFloats(0, 1, 0, 0, 0);
  4999. this.setRowFromFloats(1, 0, 1, 0, 0);
  5000. this.setRowFromFloats(2, 0, 0, 1, 0);
  5001. return this;
  5002. };
  5003. /**
  5004. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  5005. */
  5006. Matrix.prototype.multiply = function (other) {
  5007. var result = new Matrix();
  5008. this.multiplyToRef(other, result);
  5009. return result;
  5010. };
  5011. /**
  5012. * Updates the current Matrix from the passed one values.
  5013. * Returns the updated Matrix.
  5014. */
  5015. Matrix.prototype.copyFrom = function (other) {
  5016. for (var index = 0; index < 16; index++) {
  5017. this.m[index] = other.m[index];
  5018. }
  5019. this._markAsUpdated();
  5020. return this;
  5021. };
  5022. /**
  5023. * Populates the passed array from the starting index with the Matrix values.
  5024. * Returns the Matrix.
  5025. */
  5026. Matrix.prototype.copyToArray = function (array, offset) {
  5027. if (offset === void 0) { offset = 0; }
  5028. for (var index = 0; index < 16; index++) {
  5029. array[offset + index] = this.m[index];
  5030. }
  5031. return this;
  5032. };
  5033. /**
  5034. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  5035. */
  5036. Matrix.prototype.multiplyToRef = function (other, result) {
  5037. this.multiplyToArray(other, result.m, 0);
  5038. result._markAsUpdated();
  5039. return this;
  5040. };
  5041. /**
  5042. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  5043. */
  5044. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5045. var tm0 = this.m[0];
  5046. var tm1 = this.m[1];
  5047. var tm2 = this.m[2];
  5048. var tm3 = this.m[3];
  5049. var tm4 = this.m[4];
  5050. var tm5 = this.m[5];
  5051. var tm6 = this.m[6];
  5052. var tm7 = this.m[7];
  5053. var tm8 = this.m[8];
  5054. var tm9 = this.m[9];
  5055. var tm10 = this.m[10];
  5056. var tm11 = this.m[11];
  5057. var tm12 = this.m[12];
  5058. var tm13 = this.m[13];
  5059. var tm14 = this.m[14];
  5060. var tm15 = this.m[15];
  5061. var om0 = other.m[0];
  5062. var om1 = other.m[1];
  5063. var om2 = other.m[2];
  5064. var om3 = other.m[3];
  5065. var om4 = other.m[4];
  5066. var om5 = other.m[5];
  5067. var om6 = other.m[6];
  5068. var om7 = other.m[7];
  5069. var om8 = other.m[8];
  5070. var om9 = other.m[9];
  5071. var om10 = other.m[10];
  5072. var om11 = other.m[11];
  5073. var om12 = other.m[12];
  5074. var om13 = other.m[13];
  5075. var om14 = other.m[14];
  5076. var om15 = other.m[15];
  5077. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5078. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5079. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5080. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5081. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5082. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5083. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5084. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5085. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5086. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5087. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5088. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5089. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5090. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5091. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5092. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5093. return this;
  5094. };
  5095. /**
  5096. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  5097. */
  5098. Matrix.prototype.equals = function (value) {
  5099. return value &&
  5100. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5101. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5102. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5103. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5104. };
  5105. /**
  5106. * Returns a new Matrix from the current Matrix.
  5107. */
  5108. Matrix.prototype.clone = function () {
  5109. 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]);
  5110. };
  5111. /**
  5112. * Returns the string "Matrix"
  5113. */
  5114. Matrix.prototype.getClassName = function () {
  5115. return "Matrix";
  5116. };
  5117. /**
  5118. * Returns the Matrix hash code.
  5119. */
  5120. Matrix.prototype.getHashCode = function () {
  5121. var hash = this.m[0] || 0;
  5122. for (var i = 1; i < 16; i++) {
  5123. hash = (hash * 397) ^ (this.m[i] || 0);
  5124. }
  5125. return hash;
  5126. };
  5127. /**
  5128. * Decomposes the current Matrix into :
  5129. * - a scale vector3 passed as a reference to update,
  5130. * - a rotation quaternion passed as a reference to update,
  5131. * - a translation vector3 passed as a reference to update.
  5132. * Returns the true if operation was successful.
  5133. */
  5134. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5135. translation.x = this.m[12];
  5136. translation.y = this.m[13];
  5137. translation.z = this.m[14];
  5138. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5139. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5140. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5141. if (this.determinant() <= 0) {
  5142. scale.y *= -1;
  5143. }
  5144. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5145. rotation.x = 0;
  5146. rotation.y = 0;
  5147. rotation.z = 0;
  5148. rotation.w = 1;
  5149. return false;
  5150. }
  5151. 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]);
  5152. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5153. return true;
  5154. };
  5155. /**
  5156. * Returns the index-th row of the current matrix as a new Vector4.
  5157. */
  5158. Matrix.prototype.getRow = function (index) {
  5159. if (index < 0 || index > 3) {
  5160. return null;
  5161. }
  5162. var i = index * 4;
  5163. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5164. };
  5165. /**
  5166. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5167. * Returns the updated Matrix.
  5168. */
  5169. Matrix.prototype.setRow = function (index, row) {
  5170. if (index < 0 || index > 3) {
  5171. return this;
  5172. }
  5173. var i = index * 4;
  5174. this.m[i + 0] = row.x;
  5175. this.m[i + 1] = row.y;
  5176. this.m[i + 2] = row.z;
  5177. this.m[i + 3] = row.w;
  5178. this._markAsUpdated();
  5179. return this;
  5180. };
  5181. /**
  5182. * Compute the transpose of the matrix.
  5183. * Returns a new Matrix.
  5184. */
  5185. Matrix.prototype.transpose = function () {
  5186. return Matrix.Transpose(this);
  5187. };
  5188. /**
  5189. * Compute the transpose of the matrix.
  5190. * Returns the current matrix.
  5191. */
  5192. Matrix.prototype.transposeToRef = function (result) {
  5193. Matrix.TransposeToRef(this, result);
  5194. return this;
  5195. };
  5196. /**
  5197. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5198. * Returns the updated Matrix.
  5199. */
  5200. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5201. if (index < 0 || index > 3) {
  5202. return this;
  5203. }
  5204. var i = index * 4;
  5205. this.m[i + 0] = x;
  5206. this.m[i + 1] = y;
  5207. this.m[i + 2] = z;
  5208. this.m[i + 3] = w;
  5209. this._markAsUpdated();
  5210. return this;
  5211. };
  5212. /**
  5213. * Compute a new Matrix set with the current Matrix values multiplied by scale (float)
  5214. * @param scale defines the scale factor
  5215. * @returns a new Matrix
  5216. */
  5217. Matrix.prototype.scale = function (scale) {
  5218. var result = new Matrix();
  5219. this.scaleToRef(scale, result);
  5220. return result;
  5221. };
  5222. /**
  5223. * Scale the current Matrix values by a factor to a given result Matrix
  5224. * @param scale defines the scale factor
  5225. * @param result defines the Matrix to store the result
  5226. * @returns the current Matrix
  5227. */
  5228. Matrix.prototype.scaleToRef = function (scale, result) {
  5229. for (var index = 0; index < 16; index++) {
  5230. result.m[index] = this.m[index] * scale;
  5231. }
  5232. result._markAsUpdated();
  5233. return this;
  5234. };
  5235. /**
  5236. * Scale the current Matrix values by a factor and add the result to a given Matrix
  5237. * @param scale defines the scale factor
  5238. * @param result defines the Matrix to store the result
  5239. * @returns the current Matrix
  5240. */
  5241. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5242. for (var index = 0; index < 16; index++) {
  5243. result.m[index] += this.m[index] * scale;
  5244. }
  5245. result._markAsUpdated();
  5246. return this;
  5247. };
  5248. /**
  5249. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5250. * @param ref matrix to store the result
  5251. */
  5252. Matrix.prototype.toNormalMatrix = function (ref) {
  5253. this.invertToRef(ref);
  5254. ref.transpose();
  5255. var m = ref.m;
  5256. 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);
  5257. };
  5258. /**
  5259. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5260. */
  5261. Matrix.prototype.getRotationMatrix = function () {
  5262. var result = Matrix.Identity();
  5263. this.getRotationMatrixToRef(result);
  5264. return result;
  5265. };
  5266. /**
  5267. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5268. * Returns the current Matrix.
  5269. */
  5270. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5271. var m = this.m;
  5272. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5273. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5274. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5275. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5276. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5277. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5278. 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);
  5279. return this;
  5280. };
  5281. // Statics
  5282. /**
  5283. * Returns a new Matrix set from the starting index of the passed array.
  5284. */
  5285. Matrix.FromArray = function (array, offset) {
  5286. var result = new Matrix();
  5287. if (!offset) {
  5288. offset = 0;
  5289. }
  5290. Matrix.FromArrayToRef(array, offset, result);
  5291. return result;
  5292. };
  5293. /**
  5294. * Sets the passed "result" matrix from the starting index of the passed array.
  5295. */
  5296. Matrix.FromArrayToRef = function (array, offset, result) {
  5297. for (var index = 0; index < 16; index++) {
  5298. result.m[index] = array[index + offset];
  5299. }
  5300. result._markAsUpdated();
  5301. };
  5302. /**
  5303. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5304. */
  5305. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5306. for (var index = 0; index < 16; index++) {
  5307. result.m[index] = array[index + offset] * scale;
  5308. }
  5309. result._markAsUpdated();
  5310. };
  5311. /**
  5312. * Sets the passed matrix "result" with the 16 passed floats.
  5313. */
  5314. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5315. result.m[0] = initialM11;
  5316. result.m[1] = initialM12;
  5317. result.m[2] = initialM13;
  5318. result.m[3] = initialM14;
  5319. result.m[4] = initialM21;
  5320. result.m[5] = initialM22;
  5321. result.m[6] = initialM23;
  5322. result.m[7] = initialM24;
  5323. result.m[8] = initialM31;
  5324. result.m[9] = initialM32;
  5325. result.m[10] = initialM33;
  5326. result.m[11] = initialM34;
  5327. result.m[12] = initialM41;
  5328. result.m[13] = initialM42;
  5329. result.m[14] = initialM43;
  5330. result.m[15] = initialM44;
  5331. result._markAsUpdated();
  5332. };
  5333. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5334. /**
  5335. * Static identity matrix to be used as readonly matrix
  5336. * Must not be updated.
  5337. */
  5338. get: function () {
  5339. return Matrix._identityReadOnly;
  5340. },
  5341. enumerable: true,
  5342. configurable: true
  5343. });
  5344. /**
  5345. * Returns a new Matrix set from the 16 passed floats.
  5346. */
  5347. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5348. var result = new Matrix();
  5349. result.m[0] = initialM11;
  5350. result.m[1] = initialM12;
  5351. result.m[2] = initialM13;
  5352. result.m[3] = initialM14;
  5353. result.m[4] = initialM21;
  5354. result.m[5] = initialM22;
  5355. result.m[6] = initialM23;
  5356. result.m[7] = initialM24;
  5357. result.m[8] = initialM31;
  5358. result.m[9] = initialM32;
  5359. result.m[10] = initialM33;
  5360. result.m[11] = initialM34;
  5361. result.m[12] = initialM41;
  5362. result.m[13] = initialM42;
  5363. result.m[14] = initialM43;
  5364. result.m[15] = initialM44;
  5365. return result;
  5366. };
  5367. /**
  5368. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5369. */
  5370. Matrix.Compose = function (scale, rotation, translation) {
  5371. var result = Matrix.Identity();
  5372. Matrix.ComposeToRef(scale, rotation, translation, result);
  5373. return result;
  5374. };
  5375. /**
  5376. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5377. */
  5378. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5379. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5380. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5381. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5382. result.setTranslation(translation);
  5383. };
  5384. /**
  5385. * Returns a new indentity Matrix.
  5386. */
  5387. Matrix.Identity = function () {
  5388. 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);
  5389. };
  5390. /**
  5391. * Sets the passed "result" as an identity matrix.
  5392. */
  5393. Matrix.IdentityToRef = function (result) {
  5394. 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);
  5395. };
  5396. /**
  5397. * Returns a new zero Matrix.
  5398. */
  5399. Matrix.Zero = function () {
  5400. 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);
  5401. };
  5402. /**
  5403. * Returns a new rotation matrix for "angle" radians around the X axis.
  5404. */
  5405. Matrix.RotationX = function (angle) {
  5406. var result = new Matrix();
  5407. Matrix.RotationXToRef(angle, result);
  5408. return result;
  5409. };
  5410. /**
  5411. * Returns a new Matrix as the passed inverted one.
  5412. */
  5413. Matrix.Invert = function (source) {
  5414. var result = new Matrix();
  5415. source.invertToRef(result);
  5416. return result;
  5417. };
  5418. /**
  5419. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5420. */
  5421. Matrix.RotationXToRef = function (angle, result) {
  5422. var s = Math.sin(angle);
  5423. var c = Math.cos(angle);
  5424. result.m[0] = 1.0;
  5425. result.m[15] = 1.0;
  5426. result.m[5] = c;
  5427. result.m[10] = c;
  5428. result.m[9] = -s;
  5429. result.m[6] = s;
  5430. result.m[1] = 0.0;
  5431. result.m[2] = 0.0;
  5432. result.m[3] = 0.0;
  5433. result.m[4] = 0.0;
  5434. result.m[7] = 0.0;
  5435. result.m[8] = 0.0;
  5436. result.m[11] = 0.0;
  5437. result.m[12] = 0.0;
  5438. result.m[13] = 0.0;
  5439. result.m[14] = 0.0;
  5440. result._markAsUpdated();
  5441. };
  5442. /**
  5443. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5444. */
  5445. Matrix.RotationY = function (angle) {
  5446. var result = new Matrix();
  5447. Matrix.RotationYToRef(angle, result);
  5448. return result;
  5449. };
  5450. /**
  5451. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5452. */
  5453. Matrix.RotationYToRef = function (angle, result) {
  5454. var s = Math.sin(angle);
  5455. var c = Math.cos(angle);
  5456. result.m[5] = 1.0;
  5457. result.m[15] = 1.0;
  5458. result.m[0] = c;
  5459. result.m[2] = -s;
  5460. result.m[8] = s;
  5461. result.m[10] = c;
  5462. result.m[1] = 0.0;
  5463. result.m[3] = 0.0;
  5464. result.m[4] = 0.0;
  5465. result.m[6] = 0.0;
  5466. result.m[7] = 0.0;
  5467. result.m[9] = 0.0;
  5468. result.m[11] = 0.0;
  5469. result.m[12] = 0.0;
  5470. result.m[13] = 0.0;
  5471. result.m[14] = 0.0;
  5472. result._markAsUpdated();
  5473. };
  5474. /**
  5475. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5476. */
  5477. Matrix.RotationZ = function (angle) {
  5478. var result = new Matrix();
  5479. Matrix.RotationZToRef(angle, result);
  5480. return result;
  5481. };
  5482. /**
  5483. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5484. */
  5485. Matrix.RotationZToRef = function (angle, result) {
  5486. var s = Math.sin(angle);
  5487. var c = Math.cos(angle);
  5488. result.m[10] = 1.0;
  5489. result.m[15] = 1.0;
  5490. result.m[0] = c;
  5491. result.m[1] = s;
  5492. result.m[4] = -s;
  5493. result.m[5] = c;
  5494. result.m[2] = 0.0;
  5495. result.m[3] = 0.0;
  5496. result.m[6] = 0.0;
  5497. result.m[7] = 0.0;
  5498. result.m[8] = 0.0;
  5499. result.m[9] = 0.0;
  5500. result.m[11] = 0.0;
  5501. result.m[12] = 0.0;
  5502. result.m[13] = 0.0;
  5503. result.m[14] = 0.0;
  5504. result._markAsUpdated();
  5505. };
  5506. /**
  5507. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5508. */
  5509. Matrix.RotationAxis = function (axis, angle) {
  5510. var result = Matrix.Zero();
  5511. Matrix.RotationAxisToRef(axis, angle, result);
  5512. return result;
  5513. };
  5514. /**
  5515. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5516. */
  5517. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5518. var s = Math.sin(-angle);
  5519. var c = Math.cos(-angle);
  5520. var c1 = 1 - c;
  5521. axis.normalize();
  5522. result.m[0] = (axis.x * axis.x) * c1 + c;
  5523. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5524. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5525. result.m[3] = 0.0;
  5526. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5527. result.m[5] = (axis.y * axis.y) * c1 + c;
  5528. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5529. result.m[7] = 0.0;
  5530. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5531. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5532. result.m[10] = (axis.z * axis.z) * c1 + c;
  5533. result.m[11] = 0.0;
  5534. result.m[15] = 1.0;
  5535. result._markAsUpdated();
  5536. };
  5537. /**
  5538. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5539. */
  5540. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5541. var result = new Matrix();
  5542. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5543. return result;
  5544. };
  5545. /**
  5546. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5547. */
  5548. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5549. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5550. this._tempQuaternion.toRotationMatrix(result);
  5551. };
  5552. /**
  5553. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5554. */
  5555. Matrix.Scaling = function (x, y, z) {
  5556. var result = Matrix.Zero();
  5557. Matrix.ScalingToRef(x, y, z, result);
  5558. return result;
  5559. };
  5560. /**
  5561. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5562. */
  5563. Matrix.ScalingToRef = function (x, y, z, result) {
  5564. result.m[0] = x;
  5565. result.m[1] = 0.0;
  5566. result.m[2] = 0.0;
  5567. result.m[3] = 0.0;
  5568. result.m[4] = 0.0;
  5569. result.m[5] = y;
  5570. result.m[6] = 0.0;
  5571. result.m[7] = 0.0;
  5572. result.m[8] = 0.0;
  5573. result.m[9] = 0.0;
  5574. result.m[10] = z;
  5575. result.m[11] = 0.0;
  5576. result.m[12] = 0.0;
  5577. result.m[13] = 0.0;
  5578. result.m[14] = 0.0;
  5579. result.m[15] = 1.0;
  5580. result._markAsUpdated();
  5581. };
  5582. /**
  5583. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5584. */
  5585. Matrix.Translation = function (x, y, z) {
  5586. var result = Matrix.Identity();
  5587. Matrix.TranslationToRef(x, y, z, result);
  5588. return result;
  5589. };
  5590. /**
  5591. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5592. */
  5593. Matrix.TranslationToRef = function (x, y, z, result) {
  5594. 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);
  5595. };
  5596. /**
  5597. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5598. * @param startValue defines the start value
  5599. * @param endValue defines the end value
  5600. * @param gradient defines the gradient factor
  5601. * @returns the new matrix
  5602. */
  5603. Matrix.Lerp = function (startValue, endValue, gradient) {
  5604. var result = Matrix.Zero();
  5605. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5606. return result;
  5607. };
  5608. /**
  5609. * Set the passed matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5610. * @param startValue defines the start value
  5611. * @param endValue defines the end value
  5612. * @param gradient defines the gradient factor
  5613. * @param result defines the Matrix object where to store data
  5614. */
  5615. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5616. for (var index = 0; index < 16; index++) {
  5617. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5618. }
  5619. result._markAsUpdated();
  5620. };
  5621. /**
  5622. * Returns a new Matrix whose values are computed by :
  5623. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5624. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5625. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5626. */
  5627. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5628. var startScale = new Vector3(0, 0, 0);
  5629. var startRotation = new Quaternion();
  5630. var startTranslation = new Vector3(0, 0, 0);
  5631. startValue.decompose(startScale, startRotation, startTranslation);
  5632. var endScale = new Vector3(0, 0, 0);
  5633. var endRotation = new Quaternion();
  5634. var endTranslation = new Vector3(0, 0, 0);
  5635. endValue.decompose(endScale, endRotation, endTranslation);
  5636. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5637. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5638. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5639. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5640. };
  5641. /**
  5642. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5643. * This methods works for a Left-Handed system.
  5644. */
  5645. Matrix.LookAtLH = function (eye, target, up) {
  5646. var result = Matrix.Zero();
  5647. Matrix.LookAtLHToRef(eye, target, up, result);
  5648. return result;
  5649. };
  5650. /**
  5651. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5652. * This methods works for a Left-Handed system.
  5653. */
  5654. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5655. // Z axis
  5656. target.subtractToRef(eye, this._zAxis);
  5657. this._zAxis.normalize();
  5658. // X axis
  5659. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5660. if (this._xAxis.lengthSquared() === 0) {
  5661. this._xAxis.x = 1.0;
  5662. }
  5663. else {
  5664. this._xAxis.normalize();
  5665. }
  5666. // Y axis
  5667. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5668. this._yAxis.normalize();
  5669. // Eye angles
  5670. var ex = -Vector3.Dot(this._xAxis, eye);
  5671. var ey = -Vector3.Dot(this._yAxis, eye);
  5672. var ez = -Vector3.Dot(this._zAxis, eye);
  5673. 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);
  5674. };
  5675. /**
  5676. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5677. * This methods works for a Right-Handed system.
  5678. */
  5679. Matrix.LookAtRH = function (eye, target, up) {
  5680. var result = Matrix.Zero();
  5681. Matrix.LookAtRHToRef(eye, target, up, result);
  5682. return result;
  5683. };
  5684. /**
  5685. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5686. * This methods works for a Left-Handed system.
  5687. */
  5688. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5689. // Z axis
  5690. eye.subtractToRef(target, this._zAxis);
  5691. this._zAxis.normalize();
  5692. // X axis
  5693. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5694. if (this._xAxis.lengthSquared() === 0) {
  5695. this._xAxis.x = 1.0;
  5696. }
  5697. else {
  5698. this._xAxis.normalize();
  5699. }
  5700. // Y axis
  5701. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5702. this._yAxis.normalize();
  5703. // Eye angles
  5704. var ex = -Vector3.Dot(this._xAxis, eye);
  5705. var ey = -Vector3.Dot(this._yAxis, eye);
  5706. var ez = -Vector3.Dot(this._zAxis, eye);
  5707. 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);
  5708. };
  5709. /**
  5710. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5711. */
  5712. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5713. var matrix = Matrix.Zero();
  5714. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5715. return matrix;
  5716. };
  5717. /**
  5718. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5719. */
  5720. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5721. var n = znear;
  5722. var f = zfar;
  5723. var a = 2.0 / width;
  5724. var b = 2.0 / height;
  5725. var c = 2.0 / (f - n);
  5726. var d = -(f + n) / (f - n);
  5727. 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);
  5728. };
  5729. /**
  5730. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5731. */
  5732. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5733. var matrix = Matrix.Zero();
  5734. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5735. return matrix;
  5736. };
  5737. /**
  5738. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5739. */
  5740. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5741. var n = znear;
  5742. var f = zfar;
  5743. var a = 2.0 / (right - left);
  5744. var b = 2.0 / (top - bottom);
  5745. var c = 2.0 / (f - n);
  5746. var d = -(f + n) / (f - n);
  5747. var i0 = (left + right) / (left - right);
  5748. var i1 = (top + bottom) / (bottom - top);
  5749. 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);
  5750. };
  5751. /**
  5752. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5753. */
  5754. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5755. var matrix = Matrix.Zero();
  5756. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5757. return matrix;
  5758. };
  5759. /**
  5760. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5761. */
  5762. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5763. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5764. result.m[10] *= -1.0;
  5765. };
  5766. /**
  5767. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5768. */
  5769. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5770. var matrix = Matrix.Zero();
  5771. var n = znear;
  5772. var f = zfar;
  5773. var a = 2.0 * n / width;
  5774. var b = 2.0 * n / height;
  5775. var c = (f + n) / (f - n);
  5776. var d = -2.0 * f * n / (f - n);
  5777. 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);
  5778. return matrix;
  5779. };
  5780. /**
  5781. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5782. */
  5783. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5784. var matrix = Matrix.Zero();
  5785. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5786. return matrix;
  5787. };
  5788. /**
  5789. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5790. */
  5791. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5792. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5793. var n = znear;
  5794. var f = zfar;
  5795. var t = 1.0 / (Math.tan(fov * 0.5));
  5796. var a = isVerticalFovFixed ? (t / aspect) : t;
  5797. var b = isVerticalFovFixed ? t : (t * aspect);
  5798. var c = (f + n) / (f - n);
  5799. var d = -2.0 * f * n / (f - n);
  5800. 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);
  5801. };
  5802. /**
  5803. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5804. */
  5805. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5806. var matrix = Matrix.Zero();
  5807. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5808. return matrix;
  5809. };
  5810. /**
  5811. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5812. */
  5813. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5814. //alternatively this could be expressed as:
  5815. // m = PerspectiveFovLHToRef
  5816. // m[10] *= -1.0;
  5817. // m[11] *= -1.0;
  5818. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5819. var n = znear;
  5820. var f = zfar;
  5821. var t = 1.0 / (Math.tan(fov * 0.5));
  5822. var a = isVerticalFovFixed ? (t / aspect) : t;
  5823. var b = isVerticalFovFixed ? t : (t * aspect);
  5824. var c = -(f + n) / (f - n);
  5825. var d = -2 * f * n / (f - n);
  5826. 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);
  5827. };
  5828. /**
  5829. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5830. */
  5831. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5832. if (rightHanded === void 0) { rightHanded = false; }
  5833. var rightHandedFactor = rightHanded ? -1 : 1;
  5834. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5835. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5836. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5837. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5838. var xScale = 2.0 / (leftTan + rightTan);
  5839. var yScale = 2.0 / (upTan + downTan);
  5840. result.m[0] = xScale;
  5841. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5842. result.m[5] = yScale;
  5843. result.m[6] = result.m[7] = 0.0;
  5844. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5845. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5846. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5847. result.m[10] = -zfar / (znear - zfar);
  5848. result.m[11] = 1.0 * rightHandedFactor;
  5849. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5850. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5851. // result.m[14] = (znear * zfar) / (znear - zfar);
  5852. result._markAsUpdated();
  5853. };
  5854. /**
  5855. * Returns the final transformation matrix : world * view * projection * viewport
  5856. */
  5857. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5858. var cw = viewport.width;
  5859. var ch = viewport.height;
  5860. var cx = viewport.x;
  5861. var cy = viewport.y;
  5862. 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);
  5863. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5864. };
  5865. /**
  5866. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5867. */
  5868. Matrix.GetAsMatrix2x2 = function (matrix) {
  5869. return new Float32Array([
  5870. matrix.m[0], matrix.m[1],
  5871. matrix.m[4], matrix.m[5]
  5872. ]);
  5873. };
  5874. /**
  5875. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5876. */
  5877. Matrix.GetAsMatrix3x3 = function (matrix) {
  5878. return new Float32Array([
  5879. matrix.m[0], matrix.m[1], matrix.m[2],
  5880. matrix.m[4], matrix.m[5], matrix.m[6],
  5881. matrix.m[8], matrix.m[9], matrix.m[10]
  5882. ]);
  5883. };
  5884. /**
  5885. * Compute the transpose of the passed Matrix.
  5886. * Returns a new Matrix.
  5887. */
  5888. Matrix.Transpose = function (matrix) {
  5889. var result = new Matrix();
  5890. Matrix.TransposeToRef(matrix, result);
  5891. return result;
  5892. };
  5893. /**
  5894. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5895. */
  5896. Matrix.TransposeToRef = function (matrix, result) {
  5897. result.m[0] = matrix.m[0];
  5898. result.m[1] = matrix.m[4];
  5899. result.m[2] = matrix.m[8];
  5900. result.m[3] = matrix.m[12];
  5901. result.m[4] = matrix.m[1];
  5902. result.m[5] = matrix.m[5];
  5903. result.m[6] = matrix.m[9];
  5904. result.m[7] = matrix.m[13];
  5905. result.m[8] = matrix.m[2];
  5906. result.m[9] = matrix.m[6];
  5907. result.m[10] = matrix.m[10];
  5908. result.m[11] = matrix.m[14];
  5909. result.m[12] = matrix.m[3];
  5910. result.m[13] = matrix.m[7];
  5911. result.m[14] = matrix.m[11];
  5912. result.m[15] = matrix.m[15];
  5913. };
  5914. /**
  5915. * Returns a new Matrix as the reflection matrix across the passed plane.
  5916. */
  5917. Matrix.Reflection = function (plane) {
  5918. var matrix = new Matrix();
  5919. Matrix.ReflectionToRef(plane, matrix);
  5920. return matrix;
  5921. };
  5922. /**
  5923. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5924. */
  5925. Matrix.ReflectionToRef = function (plane, result) {
  5926. plane.normalize();
  5927. var x = plane.normal.x;
  5928. var y = plane.normal.y;
  5929. var z = plane.normal.z;
  5930. var temp = -2 * x;
  5931. var temp2 = -2 * y;
  5932. var temp3 = -2 * z;
  5933. result.m[0] = (temp * x) + 1;
  5934. result.m[1] = temp2 * x;
  5935. result.m[2] = temp3 * x;
  5936. result.m[3] = 0.0;
  5937. result.m[4] = temp * y;
  5938. result.m[5] = (temp2 * y) + 1;
  5939. result.m[6] = temp3 * y;
  5940. result.m[7] = 0.0;
  5941. result.m[8] = temp * z;
  5942. result.m[9] = temp2 * z;
  5943. result.m[10] = (temp3 * z) + 1;
  5944. result.m[11] = 0.0;
  5945. result.m[12] = temp * plane.d;
  5946. result.m[13] = temp2 * plane.d;
  5947. result.m[14] = temp3 * plane.d;
  5948. result.m[15] = 1.0;
  5949. result._markAsUpdated();
  5950. };
  5951. /**
  5952. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5953. */
  5954. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5955. result.m[0] = xaxis.x;
  5956. result.m[1] = xaxis.y;
  5957. result.m[2] = xaxis.z;
  5958. result.m[3] = 0.0;
  5959. result.m[4] = yaxis.x;
  5960. result.m[5] = yaxis.y;
  5961. result.m[6] = yaxis.z;
  5962. result.m[7] = 0.0;
  5963. result.m[8] = zaxis.x;
  5964. result.m[9] = zaxis.y;
  5965. result.m[10] = zaxis.z;
  5966. result.m[11] = 0.0;
  5967. result.m[12] = 0.0;
  5968. result.m[13] = 0.0;
  5969. result.m[14] = 0.0;
  5970. result.m[15] = 1.0;
  5971. result._markAsUpdated();
  5972. };
  5973. /**
  5974. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5975. */
  5976. Matrix.FromQuaternionToRef = function (quat, result) {
  5977. var xx = quat.x * quat.x;
  5978. var yy = quat.y * quat.y;
  5979. var zz = quat.z * quat.z;
  5980. var xy = quat.x * quat.y;
  5981. var zw = quat.z * quat.w;
  5982. var zx = quat.z * quat.x;
  5983. var yw = quat.y * quat.w;
  5984. var yz = quat.y * quat.z;
  5985. var xw = quat.x * quat.w;
  5986. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5987. result.m[1] = 2.0 * (xy + zw);
  5988. result.m[2] = 2.0 * (zx - yw);
  5989. result.m[3] = 0.0;
  5990. result.m[4] = 2.0 * (xy - zw);
  5991. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5992. result.m[6] = 2.0 * (yz + xw);
  5993. result.m[7] = 0.0;
  5994. result.m[8] = 2.0 * (zx + yw);
  5995. result.m[9] = 2.0 * (yz - xw);
  5996. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5997. result.m[11] = 0.0;
  5998. result.m[12] = 0.0;
  5999. result.m[13] = 0.0;
  6000. result.m[14] = 0.0;
  6001. result.m[15] = 1.0;
  6002. result._markAsUpdated();
  6003. };
  6004. Matrix._tempQuaternion = new Quaternion();
  6005. Matrix._xAxis = Vector3.Zero();
  6006. Matrix._yAxis = Vector3.Zero();
  6007. Matrix._zAxis = Vector3.Zero();
  6008. Matrix._updateFlagSeed = 0;
  6009. Matrix._identityReadOnly = Matrix.Identity();
  6010. return Matrix;
  6011. }());
  6012. BABYLON.Matrix = Matrix;
  6013. var Plane = /** @class */ (function () {
  6014. /**
  6015. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6016. */
  6017. function Plane(a, b, c, d) {
  6018. this.normal = new Vector3(a, b, c);
  6019. this.d = d;
  6020. }
  6021. /**
  6022. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6023. */
  6024. Plane.prototype.asArray = function () {
  6025. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6026. };
  6027. // Methods
  6028. /**
  6029. * Returns a new plane copied from the current Plane.
  6030. */
  6031. Plane.prototype.clone = function () {
  6032. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6033. };
  6034. /**
  6035. * Returns the string "Plane".
  6036. */
  6037. Plane.prototype.getClassName = function () {
  6038. return "Plane";
  6039. };
  6040. /**
  6041. * Returns the Plane hash code.
  6042. */
  6043. Plane.prototype.getHashCode = function () {
  6044. var hash = this.normal.getHashCode();
  6045. hash = (hash * 397) ^ (this.d || 0);
  6046. return hash;
  6047. };
  6048. /**
  6049. * Normalize the current Plane in place.
  6050. * Returns the updated Plane.
  6051. */
  6052. Plane.prototype.normalize = function () {
  6053. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6054. var magnitude = 0.0;
  6055. if (norm !== 0) {
  6056. magnitude = 1.0 / norm;
  6057. }
  6058. this.normal.x *= magnitude;
  6059. this.normal.y *= magnitude;
  6060. this.normal.z *= magnitude;
  6061. this.d *= magnitude;
  6062. return this;
  6063. };
  6064. /**
  6065. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  6066. */
  6067. Plane.prototype.transform = function (transformation) {
  6068. var transposedMatrix = Matrix.Transpose(transformation);
  6069. var x = this.normal.x;
  6070. var y = this.normal.y;
  6071. var z = this.normal.z;
  6072. var d = this.d;
  6073. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6074. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6075. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6076. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6077. return new Plane(normalX, normalY, normalZ, finalD);
  6078. };
  6079. /**
  6080. * Returns the dot product (float) of the point coordinates and the plane normal.
  6081. */
  6082. Plane.prototype.dotCoordinate = function (point) {
  6083. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6084. };
  6085. /**
  6086. * Updates the current Plane from the plane defined by the three passed points.
  6087. * Returns the updated Plane.
  6088. */
  6089. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6090. var x1 = point2.x - point1.x;
  6091. var y1 = point2.y - point1.y;
  6092. var z1 = point2.z - point1.z;
  6093. var x2 = point3.x - point1.x;
  6094. var y2 = point3.y - point1.y;
  6095. var z2 = point3.z - point1.z;
  6096. var yz = (y1 * z2) - (z1 * y2);
  6097. var xz = (z1 * x2) - (x1 * z2);
  6098. var xy = (x1 * y2) - (y1 * x2);
  6099. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6100. var invPyth;
  6101. if (pyth !== 0) {
  6102. invPyth = 1.0 / pyth;
  6103. }
  6104. else {
  6105. invPyth = 0.0;
  6106. }
  6107. this.normal.x = yz * invPyth;
  6108. this.normal.y = xz * invPyth;
  6109. this.normal.z = xy * invPyth;
  6110. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6111. return this;
  6112. };
  6113. /**
  6114. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6115. */
  6116. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6117. var dot = Vector3.Dot(this.normal, direction);
  6118. return (dot <= epsilon);
  6119. };
  6120. /**
  6121. * Returns the signed distance (float) from the passed point to the Plane.
  6122. */
  6123. Plane.prototype.signedDistanceTo = function (point) {
  6124. return Vector3.Dot(point, this.normal) + this.d;
  6125. };
  6126. // Statics
  6127. /**
  6128. * Returns a new Plane from the passed array.
  6129. */
  6130. Plane.FromArray = function (array) {
  6131. return new Plane(array[0], array[1], array[2], array[3]);
  6132. };
  6133. /**
  6134. * Returns a new Plane defined by the three passed points.
  6135. */
  6136. Plane.FromPoints = function (point1, point2, point3) {
  6137. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6138. result.copyFromPoints(point1, point2, point3);
  6139. return result;
  6140. };
  6141. /**
  6142. * Returns a new Plane the normal vector to this plane at the passed origin point.
  6143. * Note : the vector "normal" is updated because normalized.
  6144. */
  6145. Plane.FromPositionAndNormal = function (origin, normal) {
  6146. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6147. normal.normalize();
  6148. result.normal = normal;
  6149. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6150. return result;
  6151. };
  6152. /**
  6153. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  6154. */
  6155. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6156. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6157. return Vector3.Dot(point, normal) + d;
  6158. };
  6159. return Plane;
  6160. }());
  6161. BABYLON.Plane = Plane;
  6162. var Viewport = /** @class */ (function () {
  6163. /**
  6164. * Creates a Viewport object located at (x, y) and sized (width, height).
  6165. */
  6166. function Viewport(x, y, width, height) {
  6167. this.x = x;
  6168. this.y = y;
  6169. this.width = width;
  6170. this.height = height;
  6171. }
  6172. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6173. if (renderWidthOrEngine.getRenderWidth) {
  6174. var engine = renderWidthOrEngine;
  6175. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6176. }
  6177. var renderWidth = renderWidthOrEngine;
  6178. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6179. };
  6180. /**
  6181. * Returns a new Viewport copied from the current one.
  6182. */
  6183. Viewport.prototype.clone = function () {
  6184. return new Viewport(this.x, this.y, this.width, this.height);
  6185. };
  6186. return Viewport;
  6187. }());
  6188. BABYLON.Viewport = Viewport;
  6189. var Frustum = /** @class */ (function () {
  6190. function Frustum() {
  6191. }
  6192. /**
  6193. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  6194. */
  6195. Frustum.GetPlanes = function (transform) {
  6196. var frustumPlanes = [];
  6197. for (var index = 0; index < 6; index++) {
  6198. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6199. }
  6200. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6201. return frustumPlanes;
  6202. };
  6203. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6204. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6205. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6206. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6207. frustumPlane.d = transform.m[15] + transform.m[14];
  6208. frustumPlane.normalize();
  6209. };
  6210. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6211. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6212. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6213. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6214. frustumPlane.d = transform.m[15] - transform.m[14];
  6215. frustumPlane.normalize();
  6216. };
  6217. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6218. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6219. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6220. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6221. frustumPlane.d = transform.m[15] + transform.m[12];
  6222. frustumPlane.normalize();
  6223. };
  6224. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6225. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6226. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6227. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6228. frustumPlane.d = transform.m[15] - transform.m[12];
  6229. frustumPlane.normalize();
  6230. };
  6231. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6232. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6233. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6234. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6235. frustumPlane.d = transform.m[15] - transform.m[13];
  6236. frustumPlane.normalize();
  6237. };
  6238. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6239. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6240. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6241. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6242. frustumPlane.d = transform.m[15] + transform.m[13];
  6243. frustumPlane.normalize();
  6244. };
  6245. /**
  6246. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6247. */
  6248. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6249. // Near
  6250. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6251. // Far
  6252. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6253. // Left
  6254. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6255. // Right
  6256. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6257. // Top
  6258. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6259. // Bottom
  6260. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6261. };
  6262. return Frustum;
  6263. }());
  6264. BABYLON.Frustum = Frustum;
  6265. var Space;
  6266. (function (Space) {
  6267. Space[Space["LOCAL"] = 0] = "LOCAL";
  6268. Space[Space["WORLD"] = 1] = "WORLD";
  6269. Space[Space["BONE"] = 2] = "BONE";
  6270. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6271. var Axis = /** @class */ (function () {
  6272. function Axis() {
  6273. }
  6274. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6275. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6276. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6277. return Axis;
  6278. }());
  6279. BABYLON.Axis = Axis;
  6280. ;
  6281. var BezierCurve = /** @class */ (function () {
  6282. function BezierCurve() {
  6283. }
  6284. /**
  6285. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6286. */
  6287. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6288. // Extract X (which is equal to time here)
  6289. var f0 = 1 - 3 * x2 + 3 * x1;
  6290. var f1 = 3 * x2 - 6 * x1;
  6291. var f2 = 3 * x1;
  6292. var refinedT = t;
  6293. for (var i = 0; i < 5; i++) {
  6294. var refinedT2 = refinedT * refinedT;
  6295. var refinedT3 = refinedT2 * refinedT;
  6296. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6297. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6298. refinedT -= (x - t) * slope;
  6299. refinedT = Math.min(1, Math.max(0, refinedT));
  6300. }
  6301. // Resolve cubic bezier for the given x
  6302. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6303. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6304. Math.pow(refinedT, 3);
  6305. };
  6306. return BezierCurve;
  6307. }());
  6308. BABYLON.BezierCurve = BezierCurve;
  6309. var Orientation;
  6310. (function (Orientation) {
  6311. Orientation[Orientation["CW"] = 0] = "CW";
  6312. Orientation[Orientation["CCW"] = 1] = "CCW";
  6313. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6314. var Angle = /** @class */ (function () {
  6315. /**
  6316. * Creates an Angle object of "radians" radians (float).
  6317. */
  6318. function Angle(radians) {
  6319. var _this = this;
  6320. /**
  6321. * Returns the Angle value in degrees (float).
  6322. */
  6323. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6324. /**
  6325. * Returns the Angle value in radians (float).
  6326. */
  6327. this.radians = function () { return _this._radians; };
  6328. this._radians = radians;
  6329. if (this._radians < 0.0)
  6330. this._radians += (2.0 * Math.PI);
  6331. }
  6332. /**
  6333. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6334. */
  6335. Angle.BetweenTwoPoints = function (a, b) {
  6336. var delta = b.subtract(a);
  6337. var theta = Math.atan2(delta.y, delta.x);
  6338. return new Angle(theta);
  6339. };
  6340. /**
  6341. * Returns a new Angle object from the passed float in radians.
  6342. */
  6343. Angle.FromRadians = function (radians) {
  6344. return new Angle(radians);
  6345. };
  6346. /**
  6347. * Returns a new Angle object from the passed float in degrees.
  6348. */
  6349. Angle.FromDegrees = function (degrees) {
  6350. return new Angle(degrees * Math.PI / 180.0);
  6351. };
  6352. return Angle;
  6353. }());
  6354. BABYLON.Angle = Angle;
  6355. var Arc2 = /** @class */ (function () {
  6356. /**
  6357. * Creates an Arc object from the three passed points : start, middle and end.
  6358. */
  6359. function Arc2(startPoint, midPoint, endPoint) {
  6360. this.startPoint = startPoint;
  6361. this.midPoint = midPoint;
  6362. this.endPoint = endPoint;
  6363. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6364. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6365. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6366. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6367. 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);
  6368. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6369. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6370. var a1 = this.startAngle.degrees();
  6371. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6372. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6373. // angles correction
  6374. if (a2 - a1 > +180.0)
  6375. a2 -= 360.0;
  6376. if (a2 - a1 < -180.0)
  6377. a2 += 360.0;
  6378. if (a3 - a2 > +180.0)
  6379. a3 -= 360.0;
  6380. if (a3 - a2 < -180.0)
  6381. a3 += 360.0;
  6382. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6383. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6384. }
  6385. return Arc2;
  6386. }());
  6387. BABYLON.Arc2 = Arc2;
  6388. var Path2 = /** @class */ (function () {
  6389. /**
  6390. * Creates a Path2 object from the starting 2D coordinates x and y.
  6391. */
  6392. function Path2(x, y) {
  6393. this._points = new Array();
  6394. this._length = 0.0;
  6395. this.closed = false;
  6396. this._points.push(new Vector2(x, y));
  6397. }
  6398. /**
  6399. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6400. * Returns the updated Path2.
  6401. */
  6402. Path2.prototype.addLineTo = function (x, y) {
  6403. if (this.closed) {
  6404. return this;
  6405. }
  6406. var newPoint = new Vector2(x, y);
  6407. var previousPoint = this._points[this._points.length - 1];
  6408. this._points.push(newPoint);
  6409. this._length += newPoint.subtract(previousPoint).length();
  6410. return this;
  6411. };
  6412. /**
  6413. * 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.
  6414. * Returns the updated Path2.
  6415. */
  6416. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6417. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6418. if (this.closed) {
  6419. return this;
  6420. }
  6421. var startPoint = this._points[this._points.length - 1];
  6422. var midPoint = new Vector2(midX, midY);
  6423. var endPoint = new Vector2(endX, endY);
  6424. var arc = new Arc2(startPoint, midPoint, endPoint);
  6425. var increment = arc.angle.radians() / numberOfSegments;
  6426. if (arc.orientation === Orientation.CW)
  6427. increment *= -1;
  6428. var currentAngle = arc.startAngle.radians() + increment;
  6429. for (var i = 0; i < numberOfSegments; i++) {
  6430. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6431. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6432. this.addLineTo(x, y);
  6433. currentAngle += increment;
  6434. }
  6435. return this;
  6436. };
  6437. /**
  6438. * Closes the Path2.
  6439. * Returns the Path2.
  6440. */
  6441. Path2.prototype.close = function () {
  6442. this.closed = true;
  6443. return this;
  6444. };
  6445. /**
  6446. * Returns the Path2 total length (float).
  6447. */
  6448. Path2.prototype.length = function () {
  6449. var result = this._length;
  6450. if (!this.closed) {
  6451. var lastPoint = this._points[this._points.length - 1];
  6452. var firstPoint = this._points[0];
  6453. result += (firstPoint.subtract(lastPoint).length());
  6454. }
  6455. return result;
  6456. };
  6457. /**
  6458. * Returns the Path2 internal array of points.
  6459. */
  6460. Path2.prototype.getPoints = function () {
  6461. return this._points;
  6462. };
  6463. /**
  6464. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6465. */
  6466. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6467. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6468. return Vector2.Zero();
  6469. }
  6470. var lengthPosition = normalizedLengthPosition * this.length();
  6471. var previousOffset = 0;
  6472. for (var i = 0; i < this._points.length; i++) {
  6473. var j = (i + 1) % this._points.length;
  6474. var a = this._points[i];
  6475. var b = this._points[j];
  6476. var bToA = b.subtract(a);
  6477. var nextOffset = (bToA.length() + previousOffset);
  6478. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6479. var dir = bToA.normalize();
  6480. var localOffset = lengthPosition - previousOffset;
  6481. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6482. }
  6483. previousOffset = nextOffset;
  6484. }
  6485. return Vector2.Zero();
  6486. };
  6487. /**
  6488. * Returns a new Path2 starting at the coordinates (x, y).
  6489. */
  6490. Path2.StartingAt = function (x, y) {
  6491. return new Path2(x, y);
  6492. };
  6493. return Path2;
  6494. }());
  6495. BABYLON.Path2 = Path2;
  6496. var Path3D = /** @class */ (function () {
  6497. /**
  6498. * new Path3D(path, normal, raw)
  6499. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6500. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6501. * path : an array of Vector3, the curve axis of the Path3D
  6502. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6503. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6504. */
  6505. function Path3D(path, firstNormal, raw) {
  6506. if (firstNormal === void 0) { firstNormal = null; }
  6507. this.path = path;
  6508. this._curve = new Array();
  6509. this._distances = new Array();
  6510. this._tangents = new Array();
  6511. this._normals = new Array();
  6512. this._binormals = new Array();
  6513. for (var p = 0; p < path.length; p++) {
  6514. this._curve[p] = path[p].clone(); // hard copy
  6515. }
  6516. this._raw = raw || false;
  6517. this._compute(firstNormal);
  6518. }
  6519. /**
  6520. * Returns the Path3D array of successive Vector3 designing its curve.
  6521. */
  6522. Path3D.prototype.getCurve = function () {
  6523. return this._curve;
  6524. };
  6525. /**
  6526. * Returns an array populated with tangent vectors on each Path3D curve point.
  6527. */
  6528. Path3D.prototype.getTangents = function () {
  6529. return this._tangents;
  6530. };
  6531. /**
  6532. * Returns an array populated with normal vectors on each Path3D curve point.
  6533. */
  6534. Path3D.prototype.getNormals = function () {
  6535. return this._normals;
  6536. };
  6537. /**
  6538. * Returns an array populated with binormal vectors on each Path3D curve point.
  6539. */
  6540. Path3D.prototype.getBinormals = function () {
  6541. return this._binormals;
  6542. };
  6543. /**
  6544. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6545. */
  6546. Path3D.prototype.getDistances = function () {
  6547. return this._distances;
  6548. };
  6549. /**
  6550. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6551. * Returns the same object updated.
  6552. */
  6553. Path3D.prototype.update = function (path, firstNormal) {
  6554. if (firstNormal === void 0) { firstNormal = null; }
  6555. for (var p = 0; p < path.length; p++) {
  6556. this._curve[p].x = path[p].x;
  6557. this._curve[p].y = path[p].y;
  6558. this._curve[p].z = path[p].z;
  6559. }
  6560. this._compute(firstNormal);
  6561. return this;
  6562. };
  6563. // private function compute() : computes tangents, normals and binormals
  6564. Path3D.prototype._compute = function (firstNormal) {
  6565. var l = this._curve.length;
  6566. // first and last tangents
  6567. this._tangents[0] = this._getFirstNonNullVector(0);
  6568. if (!this._raw) {
  6569. this._tangents[0].normalize();
  6570. }
  6571. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6572. if (!this._raw) {
  6573. this._tangents[l - 1].normalize();
  6574. }
  6575. // normals and binormals at first point : arbitrary vector with _normalVector()
  6576. var tg0 = this._tangents[0];
  6577. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6578. this._normals[0] = pp0;
  6579. if (!this._raw) {
  6580. this._normals[0].normalize();
  6581. }
  6582. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6583. if (!this._raw) {
  6584. this._binormals[0].normalize();
  6585. }
  6586. this._distances[0] = 0.0;
  6587. // normals and binormals : next points
  6588. var prev; // previous vector (segment)
  6589. var cur; // current vector (segment)
  6590. var curTang; // current tangent
  6591. // previous normal
  6592. var prevBinor; // previous binormal
  6593. for (var i = 1; i < l; i++) {
  6594. // tangents
  6595. prev = this._getLastNonNullVector(i);
  6596. if (i < l - 1) {
  6597. cur = this._getFirstNonNullVector(i);
  6598. this._tangents[i] = prev.add(cur);
  6599. this._tangents[i].normalize();
  6600. }
  6601. this._distances[i] = this._distances[i - 1] + prev.length();
  6602. // normals and binormals
  6603. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6604. curTang = this._tangents[i];
  6605. prevBinor = this._binormals[i - 1];
  6606. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6607. if (!this._raw) {
  6608. this._normals[i].normalize();
  6609. }
  6610. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6611. if (!this._raw) {
  6612. this._binormals[i].normalize();
  6613. }
  6614. }
  6615. };
  6616. // private function getFirstNonNullVector(index)
  6617. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6618. Path3D.prototype._getFirstNonNullVector = function (index) {
  6619. var i = 1;
  6620. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6621. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6622. i++;
  6623. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6624. }
  6625. return nNVector;
  6626. };
  6627. // private function getLastNonNullVector(index)
  6628. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6629. Path3D.prototype._getLastNonNullVector = function (index) {
  6630. var i = 1;
  6631. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6632. while (nLVector.length() === 0 && index > i + 1) {
  6633. i++;
  6634. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6635. }
  6636. return nLVector;
  6637. };
  6638. // private function normalVector(v0, vt, va) :
  6639. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6640. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6641. Path3D.prototype._normalVector = function (v0, vt, va) {
  6642. var normal0;
  6643. var tgl = vt.length();
  6644. if (tgl === 0.0) {
  6645. tgl = 1.0;
  6646. }
  6647. if (va === undefined || va === null) {
  6648. var point;
  6649. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6650. point = new Vector3(0.0, -1.0, 0.0);
  6651. }
  6652. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6653. point = new Vector3(1.0, 0.0, 0.0);
  6654. }
  6655. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6656. point = new Vector3(0.0, 0.0, 1.0);
  6657. }
  6658. else {
  6659. point = Vector3.Zero();
  6660. }
  6661. normal0 = Vector3.Cross(vt, point);
  6662. }
  6663. else {
  6664. normal0 = Vector3.Cross(vt, va);
  6665. Vector3.CrossToRef(normal0, vt, normal0);
  6666. }
  6667. normal0.normalize();
  6668. return normal0;
  6669. };
  6670. return Path3D;
  6671. }());
  6672. BABYLON.Path3D = Path3D;
  6673. var Curve3 = /** @class */ (function () {
  6674. /**
  6675. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6676. * A Curve3 is designed from a series of successive Vector3.
  6677. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6678. */
  6679. function Curve3(points) {
  6680. this._length = 0.0;
  6681. this._points = points;
  6682. this._length = this._computeLength(points);
  6683. }
  6684. /**
  6685. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6686. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6687. * @param v1 (Vector3) the control point
  6688. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6689. * @param nbPoints (integer) the wanted number of points in the curve
  6690. */
  6691. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6692. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6693. var bez = new Array();
  6694. var equation = function (t, val0, val1, val2) {
  6695. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6696. return res;
  6697. };
  6698. for (var i = 0; i <= nbPoints; i++) {
  6699. 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)));
  6700. }
  6701. return new Curve3(bez);
  6702. };
  6703. /**
  6704. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6705. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6706. * @param v1 (Vector3) the first control point
  6707. * @param v2 (Vector3) the second control point
  6708. * @param v3 (Vector3) the end point of the Cubic Bezier
  6709. * @param nbPoints (integer) the wanted number of points in the curve
  6710. */
  6711. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6712. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6713. var bez = new Array();
  6714. var equation = function (t, val0, val1, val2, val3) {
  6715. 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;
  6716. return res;
  6717. };
  6718. for (var i = 0; i <= nbPoints; i++) {
  6719. 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)));
  6720. }
  6721. return new Curve3(bez);
  6722. };
  6723. /**
  6724. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6725. * @param p1 (Vector3) the origin point of the Hermite Spline
  6726. * @param t1 (Vector3) the tangent vector at the origin point
  6727. * @param p2 (Vector3) the end point of the Hermite Spline
  6728. * @param t2 (Vector3) the tangent vector at the end point
  6729. * @param nbPoints (integer) the wanted number of points in the curve
  6730. */
  6731. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6732. var hermite = new Array();
  6733. var step = 1.0 / nbPoints;
  6734. for (var i = 0; i <= nbPoints; i++) {
  6735. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6736. }
  6737. return new Curve3(hermite);
  6738. };
  6739. /**
  6740. * Returns a Curve3 object along a CatmullRom Spline curve :
  6741. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6742. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6743. */
  6744. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6745. var totalPoints = new Array();
  6746. totalPoints.push(points[0].clone());
  6747. Array.prototype.push.apply(totalPoints, points);
  6748. totalPoints.push(points[points.length - 1].clone());
  6749. var catmullRom = new Array();
  6750. var step = 1.0 / nbPoints;
  6751. var amount = 0.0;
  6752. for (var i = 0; i < totalPoints.length - 3; i++) {
  6753. amount = 0;
  6754. for (var c = 0; c < nbPoints; c++) {
  6755. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6756. amount += step;
  6757. }
  6758. }
  6759. i--;
  6760. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6761. return new Curve3(catmullRom);
  6762. };
  6763. /**
  6764. * Returns the Curve3 stored array of successive Vector3
  6765. */
  6766. Curve3.prototype.getPoints = function () {
  6767. return this._points;
  6768. };
  6769. /**
  6770. * Returns the computed length (float) of the curve.
  6771. */
  6772. Curve3.prototype.length = function () {
  6773. return this._length;
  6774. };
  6775. /**
  6776. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6777. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6778. * curveA and curveB keep unchanged.
  6779. */
  6780. Curve3.prototype.continue = function (curve) {
  6781. var lastPoint = this._points[this._points.length - 1];
  6782. var continuedPoints = this._points.slice();
  6783. var curvePoints = curve.getPoints();
  6784. for (var i = 1; i < curvePoints.length; i++) {
  6785. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6786. }
  6787. var continuedCurve = new Curve3(continuedPoints);
  6788. return continuedCurve;
  6789. };
  6790. Curve3.prototype._computeLength = function (path) {
  6791. var l = 0;
  6792. for (var i = 1; i < path.length; i++) {
  6793. l += (path[i].subtract(path[i - 1])).length();
  6794. }
  6795. return l;
  6796. };
  6797. return Curve3;
  6798. }());
  6799. BABYLON.Curve3 = Curve3;
  6800. // Vertex formats
  6801. var PositionNormalVertex = /** @class */ (function () {
  6802. function PositionNormalVertex(position, normal) {
  6803. if (position === void 0) { position = Vector3.Zero(); }
  6804. if (normal === void 0) { normal = Vector3.Up(); }
  6805. this.position = position;
  6806. this.normal = normal;
  6807. }
  6808. PositionNormalVertex.prototype.clone = function () {
  6809. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6810. };
  6811. return PositionNormalVertex;
  6812. }());
  6813. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6814. var PositionNormalTextureVertex = /** @class */ (function () {
  6815. function PositionNormalTextureVertex(position, normal, uv) {
  6816. if (position === void 0) { position = Vector3.Zero(); }
  6817. if (normal === void 0) { normal = Vector3.Up(); }
  6818. if (uv === void 0) { uv = Vector2.Zero(); }
  6819. this.position = position;
  6820. this.normal = normal;
  6821. this.uv = uv;
  6822. }
  6823. PositionNormalTextureVertex.prototype.clone = function () {
  6824. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6825. };
  6826. return PositionNormalTextureVertex;
  6827. }());
  6828. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6829. // Temporary pre-allocated objects for engine internal use
  6830. // usage in any internal function :
  6831. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6832. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6833. var Tmp = /** @class */ (function () {
  6834. function Tmp() {
  6835. }
  6836. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6837. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6838. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6839. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6840. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6841. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6842. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6843. Matrix.Zero(), Matrix.Zero(),
  6844. Matrix.Zero(), Matrix.Zero(),
  6845. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6846. return Tmp;
  6847. }());
  6848. BABYLON.Tmp = Tmp;
  6849. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6850. var MathTmp = /** @class */ (function () {
  6851. function MathTmp() {
  6852. }
  6853. MathTmp.Vector3 = [Vector3.Zero()];
  6854. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6855. MathTmp.Quaternion = [Quaternion.Zero()];
  6856. return MathTmp;
  6857. }());
  6858. })(BABYLON || (BABYLON = {}));
  6859. //# sourceMappingURL=babylon.math.js.map
  6860. var BABYLON;
  6861. (function (BABYLON) {
  6862. var Scalar = /** @class */ (function () {
  6863. function Scalar() {
  6864. }
  6865. /**
  6866. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6867. */
  6868. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6869. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6870. var num = a - b;
  6871. return -epsilon <= num && num <= epsilon;
  6872. };
  6873. /**
  6874. * Returns a string : the upper case translation of the number i to hexadecimal.
  6875. */
  6876. Scalar.ToHex = function (i) {
  6877. var str = i.toString(16);
  6878. if (i <= 15) {
  6879. return ("0" + str).toUpperCase();
  6880. }
  6881. return str.toUpperCase();
  6882. };
  6883. /**
  6884. * Returns -1 if value is negative and +1 is value is positive.
  6885. * Returns the value itself if it's equal to zero.
  6886. */
  6887. Scalar.Sign = function (value) {
  6888. value = +value; // convert to a number
  6889. if (value === 0 || isNaN(value))
  6890. return value;
  6891. return value > 0 ? 1 : -1;
  6892. };
  6893. /**
  6894. * Returns the value itself if it's between min and max.
  6895. * Returns min if the value is lower than min.
  6896. * Returns max if the value is greater than max.
  6897. */
  6898. Scalar.Clamp = function (value, min, max) {
  6899. if (min === void 0) { min = 0; }
  6900. if (max === void 0) { max = 1; }
  6901. return Math.min(max, Math.max(min, value));
  6902. };
  6903. /**
  6904. * Returns the log2 of value.
  6905. */
  6906. Scalar.Log2 = function (value) {
  6907. return Math.log(value) * Math.LOG2E;
  6908. };
  6909. /**
  6910. * Loops the value, so that it is never larger than length and never smaller than 0.
  6911. *
  6912. * This is similar to the modulo operator but it works with floating point numbers.
  6913. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6914. * With t = 5 and length = 2.5, the result would be 0.0.
  6915. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6916. */
  6917. Scalar.Repeat = function (value, length) {
  6918. return value - Math.floor(value / length) * length;
  6919. };
  6920. /**
  6921. * Normalize the value between 0.0 and 1.0 using min and max values
  6922. */
  6923. Scalar.Normalize = function (value, min, max) {
  6924. return (value - min) / (max - min);
  6925. };
  6926. /**
  6927. * Denormalize the value from 0.0 and 1.0 using min and max values
  6928. */
  6929. Scalar.Denormalize = function (normalized, min, max) {
  6930. return (normalized * (max - min) + min);
  6931. };
  6932. /**
  6933. * Calculates the shortest difference between two given angles given in degrees.
  6934. */
  6935. Scalar.DeltaAngle = function (current, target) {
  6936. var num = Scalar.Repeat(target - current, 360.0);
  6937. if (num > 180.0) {
  6938. num -= 360.0;
  6939. }
  6940. return num;
  6941. };
  6942. /**
  6943. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6944. *
  6945. * The returned value will move back and forth between 0 and length
  6946. */
  6947. Scalar.PingPong = function (tx, length) {
  6948. var t = Scalar.Repeat(tx, length * 2.0);
  6949. return length - Math.abs(t - length);
  6950. };
  6951. /**
  6952. * Interpolates between min and max with smoothing at the limits.
  6953. *
  6954. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6955. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6956. */
  6957. Scalar.SmoothStep = function (from, to, tx) {
  6958. var t = Scalar.Clamp(tx);
  6959. t = -2.0 * t * t * t + 3.0 * t * t;
  6960. return to * t + from * (1.0 - t);
  6961. };
  6962. /**
  6963. * Moves a value current towards target.
  6964. *
  6965. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6966. * Negative values of maxDelta pushes the value away from target.
  6967. */
  6968. Scalar.MoveTowards = function (current, target, maxDelta) {
  6969. var result = 0;
  6970. if (Math.abs(target - current) <= maxDelta) {
  6971. result = target;
  6972. }
  6973. else {
  6974. result = current + Scalar.Sign(target - current) * maxDelta;
  6975. }
  6976. return result;
  6977. };
  6978. /**
  6979. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6980. *
  6981. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6982. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6983. */
  6984. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6985. var num = Scalar.DeltaAngle(current, target);
  6986. var result = 0;
  6987. if (-maxDelta < num && num < maxDelta) {
  6988. result = target;
  6989. }
  6990. else {
  6991. target = current + num;
  6992. result = Scalar.MoveTowards(current, target, maxDelta);
  6993. }
  6994. return result;
  6995. };
  6996. /**
  6997. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6998. */
  6999. Scalar.Lerp = function (start, end, amount) {
  7000. return start + ((end - start) * amount);
  7001. };
  7002. /**
  7003. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7004. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7005. */
  7006. Scalar.LerpAngle = function (start, end, amount) {
  7007. var num = Scalar.Repeat(end - start, 360.0);
  7008. if (num > 180.0) {
  7009. num -= 360.0;
  7010. }
  7011. return start + num * Scalar.Clamp(amount);
  7012. };
  7013. /**
  7014. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7015. */
  7016. Scalar.InverseLerp = function (a, b, value) {
  7017. var result = 0;
  7018. if (a != b) {
  7019. result = Scalar.Clamp((value - a) / (b - a));
  7020. }
  7021. else {
  7022. result = 0.0;
  7023. }
  7024. return result;
  7025. };
  7026. /**
  7027. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7028. */
  7029. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7030. var squared = amount * amount;
  7031. var cubed = amount * squared;
  7032. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7033. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7034. var part3 = (cubed - (2.0 * squared)) + amount;
  7035. var part4 = cubed - squared;
  7036. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7037. };
  7038. /**
  7039. * Returns a random float number between and min and max values
  7040. */
  7041. Scalar.RandomRange = function (min, max) {
  7042. if (min === max)
  7043. return min;
  7044. return ((Math.random() * (max - min)) + min);
  7045. };
  7046. /**
  7047. * This function returns percentage of a number in a given range.
  7048. *
  7049. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7050. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7051. */
  7052. Scalar.RangeToPercent = function (number, min, max) {
  7053. return ((number - min) / (max - min));
  7054. };
  7055. /**
  7056. * This function returns number that corresponds to the percentage in a given range.
  7057. *
  7058. * PercentToRange(0.34,0,100) will return 34.
  7059. */
  7060. Scalar.PercentToRange = function (percent, min, max) {
  7061. return ((max - min) * percent + min);
  7062. };
  7063. /**
  7064. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7065. * @param angle The angle to normalize in radian.
  7066. * @return The converted angle.
  7067. */
  7068. Scalar.NormalizeRadians = function (angle) {
  7069. // More precise but slower version kept for reference.
  7070. // angle = angle % Tools.TwoPi;
  7071. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7072. //if (angle > Math.PI) {
  7073. // angle -= Tools.TwoPi;
  7074. //}
  7075. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7076. return angle;
  7077. };
  7078. /**
  7079. * Two pi constants convenient for computation.
  7080. */
  7081. Scalar.TwoPi = Math.PI * 2;
  7082. return Scalar;
  7083. }());
  7084. BABYLON.Scalar = Scalar;
  7085. })(BABYLON || (BABYLON = {}));
  7086. //# sourceMappingURL=babylon.math.scalar.js.map
  7087. //# sourceMappingURL=babylon.mixins.js.map
  7088. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7089. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7090. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7091. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7092. //# sourceMappingURL=babylon.webgl2.js.map
  7093. var BABYLON;
  7094. (function (BABYLON) {
  7095. var __decoratorInitialStore = {};
  7096. var __mergedStore = {};
  7097. var _copySource = function (creationFunction, source, instanciate) {
  7098. var destination = creationFunction();
  7099. // Tags
  7100. if (BABYLON.Tags) {
  7101. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7102. }
  7103. var classStore = getMergedStore(destination);
  7104. // Properties
  7105. for (var property in classStore) {
  7106. var propertyDescriptor = classStore[property];
  7107. var sourceProperty = source[property];
  7108. var propertyType = propertyDescriptor.type;
  7109. if (sourceProperty !== undefined && sourceProperty !== null) {
  7110. switch (propertyType) {
  7111. case 0: // Value
  7112. case 6:// Mesh reference
  7113. destination[property] = sourceProperty;
  7114. break;
  7115. case 1:// Texture
  7116. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7117. break;
  7118. case 2: // Color3
  7119. case 3: // FresnelParameters
  7120. case 4: // Vector2
  7121. case 5: // Vector3
  7122. case 7: // Color Curves
  7123. case 10:// Quaternion
  7124. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7125. break;
  7126. }
  7127. }
  7128. }
  7129. return destination;
  7130. };
  7131. function getDirectStore(target) {
  7132. var classKey = target.getClassName();
  7133. if (!__decoratorInitialStore[classKey]) {
  7134. __decoratorInitialStore[classKey] = {};
  7135. }
  7136. return __decoratorInitialStore[classKey];
  7137. }
  7138. /**
  7139. * Return the list of properties flagged as serializable
  7140. * @param target: host object
  7141. */
  7142. function getMergedStore(target) {
  7143. var classKey = target.getClassName();
  7144. if (__mergedStore[classKey]) {
  7145. return __mergedStore[classKey];
  7146. }
  7147. __mergedStore[classKey] = {};
  7148. var store = __mergedStore[classKey];
  7149. var currentTarget = target;
  7150. var currentKey = classKey;
  7151. while (currentKey) {
  7152. var initialStore = __decoratorInitialStore[currentKey];
  7153. for (var property in initialStore) {
  7154. store[property] = initialStore[property];
  7155. }
  7156. var parent_1 = void 0;
  7157. var done = false;
  7158. do {
  7159. parent_1 = Object.getPrototypeOf(currentTarget);
  7160. if (!parent_1.getClassName) {
  7161. done = true;
  7162. break;
  7163. }
  7164. if (parent_1.getClassName() !== currentKey) {
  7165. break;
  7166. }
  7167. currentTarget = parent_1;
  7168. } while (parent_1);
  7169. if (done) {
  7170. break;
  7171. }
  7172. currentKey = parent_1.getClassName();
  7173. currentTarget = parent_1;
  7174. }
  7175. return store;
  7176. }
  7177. function generateSerializableMember(type, sourceName) {
  7178. return function (target, propertyKey) {
  7179. var classStore = getDirectStore(target);
  7180. if (!classStore[propertyKey]) {
  7181. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7182. }
  7183. };
  7184. }
  7185. function generateExpandMember(setCallback, targetKey) {
  7186. if (targetKey === void 0) { targetKey = null; }
  7187. return function (target, propertyKey) {
  7188. var key = targetKey || ("_" + propertyKey);
  7189. Object.defineProperty(target, propertyKey, {
  7190. get: function () {
  7191. return this[key];
  7192. },
  7193. set: function (value) {
  7194. if (this[key] === value) {
  7195. return;
  7196. }
  7197. this[key] = value;
  7198. target[setCallback].apply(this);
  7199. },
  7200. enumerable: true,
  7201. configurable: true
  7202. });
  7203. };
  7204. }
  7205. function expandToProperty(callback, targetKey) {
  7206. if (targetKey === void 0) { targetKey = null; }
  7207. return generateExpandMember(callback, targetKey);
  7208. }
  7209. BABYLON.expandToProperty = expandToProperty;
  7210. function serialize(sourceName) {
  7211. return generateSerializableMember(0, sourceName); // value member
  7212. }
  7213. BABYLON.serialize = serialize;
  7214. function serializeAsTexture(sourceName) {
  7215. return generateSerializableMember(1, sourceName); // texture member
  7216. }
  7217. BABYLON.serializeAsTexture = serializeAsTexture;
  7218. function serializeAsColor3(sourceName) {
  7219. return generateSerializableMember(2, sourceName); // color3 member
  7220. }
  7221. BABYLON.serializeAsColor3 = serializeAsColor3;
  7222. function serializeAsFresnelParameters(sourceName) {
  7223. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7224. }
  7225. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7226. function serializeAsVector2(sourceName) {
  7227. return generateSerializableMember(4, sourceName); // vector2 member
  7228. }
  7229. BABYLON.serializeAsVector2 = serializeAsVector2;
  7230. function serializeAsVector3(sourceName) {
  7231. return generateSerializableMember(5, sourceName); // vector3 member
  7232. }
  7233. BABYLON.serializeAsVector3 = serializeAsVector3;
  7234. function serializeAsMeshReference(sourceName) {
  7235. return generateSerializableMember(6, sourceName); // mesh reference member
  7236. }
  7237. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7238. function serializeAsColorCurves(sourceName) {
  7239. return generateSerializableMember(7, sourceName); // color curves
  7240. }
  7241. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7242. function serializeAsColor4(sourceName) {
  7243. return generateSerializableMember(8, sourceName); // color 4
  7244. }
  7245. BABYLON.serializeAsColor4 = serializeAsColor4;
  7246. function serializeAsImageProcessingConfiguration(sourceName) {
  7247. return generateSerializableMember(9, sourceName); // image processing
  7248. }
  7249. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7250. function serializeAsQuaternion(sourceName) {
  7251. return generateSerializableMember(10, sourceName); // quaternion member
  7252. }
  7253. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7254. var SerializationHelper = /** @class */ (function () {
  7255. function SerializationHelper() {
  7256. }
  7257. SerializationHelper.Serialize = function (entity, serializationObject) {
  7258. if (!serializationObject) {
  7259. serializationObject = {};
  7260. }
  7261. // Tags
  7262. if (BABYLON.Tags) {
  7263. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7264. }
  7265. var serializedProperties = getMergedStore(entity);
  7266. // Properties
  7267. for (var property in serializedProperties) {
  7268. var propertyDescriptor = serializedProperties[property];
  7269. var targetPropertyName = propertyDescriptor.sourceName || property;
  7270. var propertyType = propertyDescriptor.type;
  7271. var sourceProperty = entity[property];
  7272. if (sourceProperty !== undefined && sourceProperty !== null) {
  7273. switch (propertyType) {
  7274. case 0:// Value
  7275. serializationObject[targetPropertyName] = sourceProperty;
  7276. break;
  7277. case 1:// Texture
  7278. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7279. break;
  7280. case 2:// Color3
  7281. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7282. break;
  7283. case 3:// FresnelParameters
  7284. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7285. break;
  7286. case 4:// Vector2
  7287. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7288. break;
  7289. case 5:// Vector3
  7290. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7291. break;
  7292. case 6:// Mesh reference
  7293. serializationObject[targetPropertyName] = sourceProperty.id;
  7294. break;
  7295. case 7:// Color Curves
  7296. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7297. break;
  7298. case 8:// Color 4
  7299. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7300. break;
  7301. case 9:// Image Processing
  7302. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7303. break;
  7304. }
  7305. }
  7306. }
  7307. return serializationObject;
  7308. };
  7309. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7310. if (rootUrl === void 0) { rootUrl = null; }
  7311. var destination = creationFunction();
  7312. if (!rootUrl) {
  7313. rootUrl = "";
  7314. }
  7315. // Tags
  7316. if (BABYLON.Tags) {
  7317. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7318. }
  7319. var classStore = getMergedStore(destination);
  7320. // Properties
  7321. for (var property in classStore) {
  7322. var propertyDescriptor = classStore[property];
  7323. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7324. var propertyType = propertyDescriptor.type;
  7325. if (sourceProperty !== undefined && sourceProperty !== null) {
  7326. var dest = destination;
  7327. switch (propertyType) {
  7328. case 0:// Value
  7329. dest[property] = sourceProperty;
  7330. break;
  7331. case 1:// Texture
  7332. if (scene) {
  7333. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7334. }
  7335. break;
  7336. case 2:// Color3
  7337. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7338. break;
  7339. case 3:// FresnelParameters
  7340. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7341. break;
  7342. case 4:// Vector2
  7343. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7344. break;
  7345. case 5:// Vector3
  7346. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7347. break;
  7348. case 6:// Mesh reference
  7349. if (scene) {
  7350. dest[property] = scene.getLastMeshByID(sourceProperty);
  7351. }
  7352. break;
  7353. case 7:// Color Curves
  7354. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7355. break;
  7356. case 8:// Color 4
  7357. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7358. break;
  7359. case 9:// Image Processing
  7360. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7361. break;
  7362. }
  7363. }
  7364. }
  7365. return destination;
  7366. };
  7367. SerializationHelper.Clone = function (creationFunction, source) {
  7368. return _copySource(creationFunction, source, false);
  7369. };
  7370. SerializationHelper.Instanciate = function (creationFunction, source) {
  7371. return _copySource(creationFunction, source, true);
  7372. };
  7373. return SerializationHelper;
  7374. }());
  7375. BABYLON.SerializationHelper = SerializationHelper;
  7376. })(BABYLON || (BABYLON = {}));
  7377. //# sourceMappingURL=babylon.decorators.js.map
  7378. var BABYLON;
  7379. (function (BABYLON) {
  7380. /**
  7381. * Wrapper class for promise with external resolve and reject.
  7382. */
  7383. var Deferred = /** @class */ (function () {
  7384. /**
  7385. * Constructor for this deferred object.
  7386. */
  7387. function Deferred() {
  7388. var _this = this;
  7389. this.promise = new Promise(function (resolve, reject) {
  7390. _this._resolve = resolve;
  7391. _this._reject = reject;
  7392. });
  7393. }
  7394. Object.defineProperty(Deferred.prototype, "resolve", {
  7395. /**
  7396. * The resolve method of the promise associated with this deferred object.
  7397. */
  7398. get: function () {
  7399. return this._resolve;
  7400. },
  7401. enumerable: true,
  7402. configurable: true
  7403. });
  7404. Object.defineProperty(Deferred.prototype, "reject", {
  7405. /**
  7406. * The reject method of the promise associated with this deferred object.
  7407. */
  7408. get: function () {
  7409. return this._reject;
  7410. },
  7411. enumerable: true,
  7412. configurable: true
  7413. });
  7414. return Deferred;
  7415. }());
  7416. BABYLON.Deferred = Deferred;
  7417. })(BABYLON || (BABYLON = {}));
  7418. //# sourceMappingURL=babylon.deferred.js.map
  7419. var BABYLON;
  7420. (function (BABYLON) {
  7421. /**
  7422. * A class serves as a medium between the observable and its observers
  7423. */
  7424. var EventState = /** @class */ (function () {
  7425. /**
  7426. * Create a new EventState
  7427. * @param mask defines the mask associated with this state
  7428. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7429. * @param target defines the original target of the state
  7430. * @param currentTarget defines the current target of the state
  7431. */
  7432. function EventState(mask, skipNextObservers, target, currentTarget) {
  7433. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7434. this.initalize(mask, skipNextObservers, target, currentTarget);
  7435. }
  7436. /**
  7437. * Initialize the current event state
  7438. * @param mask defines the mask associated with this state
  7439. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7440. * @param target defines the original target of the state
  7441. * @param currentTarget defines the current target of the state
  7442. * @returns the current event state
  7443. */
  7444. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7445. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7446. this.mask = mask;
  7447. this.skipNextObservers = skipNextObservers;
  7448. this.target = target;
  7449. this.currentTarget = currentTarget;
  7450. return this;
  7451. };
  7452. return EventState;
  7453. }());
  7454. BABYLON.EventState = EventState;
  7455. /**
  7456. * Represent an Observer registered to a given Observable object.
  7457. */
  7458. var Observer = /** @class */ (function () {
  7459. /**
  7460. * Creates a new observer
  7461. * @param callback defines the callback to call when the observer is notified
  7462. * @param mask defines the mask of the observer (used to filter notifications)
  7463. * @param scope defines the current scope used to restore the JS context
  7464. */
  7465. function Observer(
  7466. /**
  7467. * Defines the callback to call when the observer is notified
  7468. */
  7469. callback,
  7470. /**
  7471. * Defines the mask of the observer (used to filter notifications)
  7472. */
  7473. mask,
  7474. /**
  7475. * Defines the current scope used to restore the JS context
  7476. */
  7477. scope) {
  7478. if (scope === void 0) { scope = null; }
  7479. this.callback = callback;
  7480. this.mask = mask;
  7481. this.scope = scope;
  7482. /** @ignore */
  7483. this._willBeUnregistered = false;
  7484. /**
  7485. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7486. */
  7487. this.unregisterOnNextCall = false;
  7488. }
  7489. return Observer;
  7490. }());
  7491. BABYLON.Observer = Observer;
  7492. /**
  7493. * Represent a list of observers registered to multiple Observables object.
  7494. */
  7495. var MultiObserver = /** @class */ (function () {
  7496. function MultiObserver() {
  7497. }
  7498. /**
  7499. * Release associated resources
  7500. */
  7501. MultiObserver.prototype.dispose = function () {
  7502. if (this._observers && this._observables) {
  7503. for (var index = 0; index < this._observers.length; index++) {
  7504. this._observables[index].remove(this._observers[index]);
  7505. }
  7506. }
  7507. this._observers = null;
  7508. this._observables = null;
  7509. };
  7510. /**
  7511. * Raise a callback when one of the observable will notify
  7512. * @param observables defines a list of observables to watch
  7513. * @param callback defines the callback to call on notification
  7514. * @param mask defines the mask used to filter notifications
  7515. * @param scope defines the current scope used to restore the JS context
  7516. * @returns the new MultiObserver
  7517. */
  7518. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7519. if (mask === void 0) { mask = -1; }
  7520. if (scope === void 0) { scope = null; }
  7521. var result = new MultiObserver();
  7522. result._observers = new Array();
  7523. result._observables = observables;
  7524. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7525. var observable = observables_1[_i];
  7526. var observer = observable.add(callback, mask, false, scope);
  7527. if (observer) {
  7528. result._observers.push(observer);
  7529. }
  7530. }
  7531. return result;
  7532. };
  7533. return MultiObserver;
  7534. }());
  7535. BABYLON.MultiObserver = MultiObserver;
  7536. /**
  7537. * The Observable class is a simple implementation of the Observable pattern.
  7538. * 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.
  7539. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7540. * 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).
  7541. * 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.
  7542. */
  7543. var Observable = /** @class */ (function () {
  7544. /**
  7545. * Creates a new observable
  7546. * @param onObserverAdded defines a callback to call when a new observer is added
  7547. */
  7548. function Observable(onObserverAdded) {
  7549. this._observers = new Array();
  7550. this._eventState = new EventState(0);
  7551. if (onObserverAdded) {
  7552. this._onObserverAdded = onObserverAdded;
  7553. }
  7554. }
  7555. /**
  7556. * Create a new Observer with the specified callback
  7557. * @param callback the callback that will be executed for that Observer
  7558. * @param mask the mask used to filter observers
  7559. * @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.
  7560. * @param scope optional scope for the callback to be called from
  7561. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7562. * @returns the new observer created for the callback
  7563. */
  7564. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7565. if (mask === void 0) { mask = -1; }
  7566. if (insertFirst === void 0) { insertFirst = false; }
  7567. if (scope === void 0) { scope = null; }
  7568. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7569. if (!callback) {
  7570. return null;
  7571. }
  7572. var observer = new Observer(callback, mask, scope);
  7573. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7574. if (insertFirst) {
  7575. this._observers.unshift(observer);
  7576. }
  7577. else {
  7578. this._observers.push(observer);
  7579. }
  7580. if (this._onObserverAdded) {
  7581. this._onObserverAdded(observer);
  7582. }
  7583. return observer;
  7584. };
  7585. /**
  7586. * Remove an Observer from the Observable object
  7587. * @param observer the instance of the Observer to remove
  7588. * @returns false if it doesn't belong to this Observable
  7589. */
  7590. Observable.prototype.remove = function (observer) {
  7591. if (!observer) {
  7592. return false;
  7593. }
  7594. var index = this._observers.indexOf(observer);
  7595. if (index !== -1) {
  7596. this._observers.splice(index, 1);
  7597. return true;
  7598. }
  7599. return false;
  7600. };
  7601. /**
  7602. * Remove a callback from the Observable object
  7603. * @param callback the callback to remove
  7604. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7605. * @returns false if it doesn't belong to this Observable
  7606. */
  7607. Observable.prototype.removeCallback = function (callback, scope) {
  7608. for (var index = 0; index < this._observers.length; index++) {
  7609. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7610. this._observers.splice(index, 1);
  7611. return true;
  7612. }
  7613. }
  7614. return false;
  7615. };
  7616. Observable.prototype._deferUnregister = function (observer) {
  7617. var _this = this;
  7618. observer.unregisterOnNextCall = false;
  7619. observer._willBeUnregistered = true;
  7620. BABYLON.Tools.SetImmediate(function () {
  7621. _this.remove(observer);
  7622. });
  7623. };
  7624. /**
  7625. * Notify all Observers by calling their respective callback with the given data
  7626. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7627. * @param eventData defines the data to send to all observers
  7628. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7629. * @param target defines the original target of the state
  7630. * @param currentTarget defines the current target of the state
  7631. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7632. */
  7633. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7634. if (mask === void 0) { mask = -1; }
  7635. if (!this._observers.length) {
  7636. return true;
  7637. }
  7638. var state = this._eventState;
  7639. state.mask = mask;
  7640. state.target = target;
  7641. state.currentTarget = currentTarget;
  7642. state.skipNextObservers = false;
  7643. state.lastReturnValue = eventData;
  7644. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7645. var obs = _a[_i];
  7646. if (obs._willBeUnregistered) {
  7647. continue;
  7648. }
  7649. if (obs.mask & mask) {
  7650. if (obs.scope) {
  7651. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7652. }
  7653. else {
  7654. state.lastReturnValue = obs.callback(eventData, state);
  7655. }
  7656. if (obs.unregisterOnNextCall) {
  7657. this._deferUnregister(obs);
  7658. }
  7659. }
  7660. if (state.skipNextObservers) {
  7661. return false;
  7662. }
  7663. }
  7664. return true;
  7665. };
  7666. /**
  7667. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7668. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7669. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7670. * and it is crucial that all callbacks will be executed.
  7671. * The order of the callbacks is kept, callbacks are not executed parallel.
  7672. *
  7673. * @param eventData The data to be sent to each callback
  7674. * @param mask is used to filter observers defaults to -1
  7675. * @param target defines the callback target (see EventState)
  7676. * @param currentTarget defines he current object in the bubbling phase
  7677. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7678. */
  7679. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7680. var _this = this;
  7681. if (mask === void 0) { mask = -1; }
  7682. // create an empty promise
  7683. var p = Promise.resolve(eventData);
  7684. // no observers? return this promise.
  7685. if (!this._observers.length) {
  7686. return p;
  7687. }
  7688. var state = this._eventState;
  7689. state.mask = mask;
  7690. state.target = target;
  7691. state.currentTarget = currentTarget;
  7692. state.skipNextObservers = false;
  7693. // execute one callback after another (not using Promise.all, the order is important)
  7694. this._observers.forEach(function (obs) {
  7695. if (state.skipNextObservers) {
  7696. return;
  7697. }
  7698. if (obs._willBeUnregistered) {
  7699. return;
  7700. }
  7701. if (obs.mask & mask) {
  7702. if (obs.scope) {
  7703. p = p.then(function (lastReturnedValue) {
  7704. state.lastReturnValue = lastReturnedValue;
  7705. return obs.callback.apply(obs.scope, [eventData, state]);
  7706. });
  7707. }
  7708. else {
  7709. p = p.then(function (lastReturnedValue) {
  7710. state.lastReturnValue = lastReturnedValue;
  7711. return obs.callback(eventData, state);
  7712. });
  7713. }
  7714. if (obs.unregisterOnNextCall) {
  7715. _this._deferUnregister(obs);
  7716. }
  7717. }
  7718. });
  7719. // return the eventData
  7720. return p.then(function () { return eventData; });
  7721. };
  7722. /**
  7723. * Notify a specific observer
  7724. * @param observer defines the observer to notify
  7725. * @param eventData defines the data to be sent to each callback
  7726. * @param mask is used to filter observers defaults to -1
  7727. */
  7728. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7729. if (mask === void 0) { mask = -1; }
  7730. var state = this._eventState;
  7731. state.mask = mask;
  7732. state.skipNextObservers = false;
  7733. observer.callback(eventData, state);
  7734. };
  7735. /**
  7736. * Gets a boolean indicating if the observable has at least one observer
  7737. * @returns true is the Observable has at least one Observer registered
  7738. */
  7739. Observable.prototype.hasObservers = function () {
  7740. return this._observers.length > 0;
  7741. };
  7742. /**
  7743. * Clear the list of observers
  7744. */
  7745. Observable.prototype.clear = function () {
  7746. this._observers = new Array();
  7747. this._onObserverAdded = null;
  7748. };
  7749. /**
  7750. * Clone the current observable
  7751. * @returns a new observable
  7752. */
  7753. Observable.prototype.clone = function () {
  7754. var result = new Observable();
  7755. result._observers = this._observers.slice(0);
  7756. return result;
  7757. };
  7758. /**
  7759. * Does this observable handles observer registered with a given mask
  7760. * @param mask defines the mask to be tested
  7761. * @return whether or not one observer registered with the given mask is handeled
  7762. **/
  7763. Observable.prototype.hasSpecificMask = function (mask) {
  7764. if (mask === void 0) { mask = -1; }
  7765. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7766. var obs = _a[_i];
  7767. if (obs.mask & mask || obs.mask === mask) {
  7768. return true;
  7769. }
  7770. }
  7771. return false;
  7772. };
  7773. return Observable;
  7774. }());
  7775. BABYLON.Observable = Observable;
  7776. })(BABYLON || (BABYLON = {}));
  7777. //# sourceMappingURL=babylon.observable.js.map
  7778. var BABYLON;
  7779. (function (BABYLON) {
  7780. var SmartArray = /** @class */ (function () {
  7781. function SmartArray(capacity) {
  7782. this.length = 0;
  7783. this.data = new Array(capacity);
  7784. this._id = SmartArray._GlobalId++;
  7785. }
  7786. SmartArray.prototype.push = function (value) {
  7787. this.data[this.length++] = value;
  7788. if (this.length > this.data.length) {
  7789. this.data.length *= 2;
  7790. }
  7791. };
  7792. SmartArray.prototype.forEach = function (func) {
  7793. for (var index = 0; index < this.length; index++) {
  7794. func(this.data[index]);
  7795. }
  7796. };
  7797. SmartArray.prototype.sort = function (compareFn) {
  7798. this.data.sort(compareFn);
  7799. };
  7800. SmartArray.prototype.reset = function () {
  7801. this.length = 0;
  7802. };
  7803. SmartArray.prototype.dispose = function () {
  7804. this.reset();
  7805. if (this.data) {
  7806. this.data.length = 0;
  7807. this.data = [];
  7808. }
  7809. };
  7810. SmartArray.prototype.concat = function (array) {
  7811. if (array.length === 0) {
  7812. return;
  7813. }
  7814. if (this.length + array.length > this.data.length) {
  7815. this.data.length = (this.length + array.length) * 2;
  7816. }
  7817. for (var index = 0; index < array.length; index++) {
  7818. this.data[this.length++] = (array.data || array)[index];
  7819. }
  7820. };
  7821. SmartArray.prototype.indexOf = function (value) {
  7822. var position = this.data.indexOf(value);
  7823. if (position >= this.length) {
  7824. return -1;
  7825. }
  7826. return position;
  7827. };
  7828. SmartArray.prototype.contains = function (value) {
  7829. return this.data.indexOf(value) !== -1;
  7830. };
  7831. // Statics
  7832. SmartArray._GlobalId = 0;
  7833. return SmartArray;
  7834. }());
  7835. BABYLON.SmartArray = SmartArray;
  7836. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7837. __extends(SmartArrayNoDuplicate, _super);
  7838. function SmartArrayNoDuplicate() {
  7839. var _this = _super !== null && _super.apply(this, arguments) || this;
  7840. _this._duplicateId = 0;
  7841. return _this;
  7842. }
  7843. SmartArrayNoDuplicate.prototype.push = function (value) {
  7844. _super.prototype.push.call(this, value);
  7845. if (!value.__smartArrayFlags) {
  7846. value.__smartArrayFlags = {};
  7847. }
  7848. value.__smartArrayFlags[this._id] = this._duplicateId;
  7849. };
  7850. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7851. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7852. return false;
  7853. }
  7854. this.push(value);
  7855. return true;
  7856. };
  7857. SmartArrayNoDuplicate.prototype.reset = function () {
  7858. _super.prototype.reset.call(this);
  7859. this._duplicateId++;
  7860. };
  7861. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7862. if (array.length === 0) {
  7863. return;
  7864. }
  7865. if (this.length + array.length > this.data.length) {
  7866. this.data.length = (this.length + array.length) * 2;
  7867. }
  7868. for (var index = 0; index < array.length; index++) {
  7869. var item = (array.data || array)[index];
  7870. this.pushNoDuplicate(item);
  7871. }
  7872. };
  7873. return SmartArrayNoDuplicate;
  7874. }(SmartArray));
  7875. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7876. })(BABYLON || (BABYLON = {}));
  7877. //# sourceMappingURL=babylon.smartArray.js.map
  7878. var BABYLON;
  7879. (function (BABYLON) {
  7880. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7881. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7882. var LoadFileError = /** @class */ (function (_super) {
  7883. __extends(LoadFileError, _super);
  7884. function LoadFileError(message, request) {
  7885. var _this = _super.call(this, message) || this;
  7886. _this.request = request;
  7887. _this.name = "LoadFileError";
  7888. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7889. return _this;
  7890. }
  7891. // Polyfill for Object.setPrototypeOf if necessary.
  7892. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7893. return LoadFileError;
  7894. }(Error));
  7895. BABYLON.LoadFileError = LoadFileError;
  7896. var RetryStrategy = /** @class */ (function () {
  7897. function RetryStrategy() {
  7898. }
  7899. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7900. if (maxRetries === void 0) { maxRetries = 3; }
  7901. if (baseInterval === void 0) { baseInterval = 500; }
  7902. return function (url, request, retryIndex) {
  7903. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7904. return -1;
  7905. }
  7906. return Math.pow(2, retryIndex) * baseInterval;
  7907. };
  7908. };
  7909. return RetryStrategy;
  7910. }());
  7911. BABYLON.RetryStrategy = RetryStrategy;
  7912. // Screenshots
  7913. var screenshotCanvas;
  7914. var cloneValue = function (source, destinationObject) {
  7915. if (!source)
  7916. return null;
  7917. if (source instanceof BABYLON.Mesh) {
  7918. return null;
  7919. }
  7920. if (source instanceof BABYLON.SubMesh) {
  7921. return source.clone(destinationObject);
  7922. }
  7923. else if (source.clone) {
  7924. return source.clone();
  7925. }
  7926. return null;
  7927. };
  7928. var Tools = /** @class */ (function () {
  7929. function Tools() {
  7930. }
  7931. /**
  7932. * Interpolates between a and b via alpha
  7933. * @param a The lower value (returned when alpha = 0)
  7934. * @param b The upper value (returned when alpha = 1)
  7935. * @param alpha The interpolation-factor
  7936. * @return The mixed value
  7937. */
  7938. Tools.Mix = function (a, b, alpha) {
  7939. return a * (1 - alpha) + b * alpha;
  7940. };
  7941. Tools.Instantiate = function (className) {
  7942. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7943. return Tools.RegisteredExternalClasses[className];
  7944. }
  7945. var arr = className.split(".");
  7946. var fn = (window || this);
  7947. for (var i = 0, len = arr.length; i < len; i++) {
  7948. fn = fn[arr[i]];
  7949. }
  7950. if (typeof fn !== "function") {
  7951. return null;
  7952. }
  7953. return fn;
  7954. };
  7955. /**
  7956. * Provides a slice function that will work even on IE
  7957. * @param data defines the array to slice
  7958. * @returns the new sliced array
  7959. */
  7960. Tools.Slice = function (data) {
  7961. if (data.slice) {
  7962. return data.slice();
  7963. }
  7964. return Array.prototype.slice.call(data);
  7965. };
  7966. Tools.SetImmediate = function (action) {
  7967. if (window.setImmediate) {
  7968. window.setImmediate(action);
  7969. }
  7970. else {
  7971. setTimeout(action, 1);
  7972. }
  7973. };
  7974. Tools.IsExponentOfTwo = function (value) {
  7975. var count = 1;
  7976. do {
  7977. count *= 2;
  7978. } while (count < value);
  7979. return count === value;
  7980. };
  7981. /**
  7982. * Find the next highest power of two.
  7983. * @param x Number to start search from.
  7984. * @return Next highest power of two.
  7985. */
  7986. Tools.CeilingPOT = function (x) {
  7987. x--;
  7988. x |= x >> 1;
  7989. x |= x >> 2;
  7990. x |= x >> 4;
  7991. x |= x >> 8;
  7992. x |= x >> 16;
  7993. x++;
  7994. return x;
  7995. };
  7996. /**
  7997. * Find the next lowest power of two.
  7998. * @param x Number to start search from.
  7999. * @return Next lowest power of two.
  8000. */
  8001. Tools.FloorPOT = function (x) {
  8002. x = x | (x >> 1);
  8003. x = x | (x >> 2);
  8004. x = x | (x >> 4);
  8005. x = x | (x >> 8);
  8006. x = x | (x >> 16);
  8007. return x - (x >> 1);
  8008. };
  8009. /**
  8010. * Find the nearest power of two.
  8011. * @param x Number to start search from.
  8012. * @return Next nearest power of two.
  8013. */
  8014. Tools.NearestPOT = function (x) {
  8015. var c = Tools.CeilingPOT(x);
  8016. var f = Tools.FloorPOT(x);
  8017. return (c - x) > (x - f) ? f : c;
  8018. };
  8019. Tools.GetExponentOfTwo = function (value, max, mode) {
  8020. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8021. var pot;
  8022. switch (mode) {
  8023. case BABYLON.Engine.SCALEMODE_FLOOR:
  8024. pot = Tools.FloorPOT(value);
  8025. break;
  8026. case BABYLON.Engine.SCALEMODE_NEAREST:
  8027. pot = Tools.NearestPOT(value);
  8028. break;
  8029. case BABYLON.Engine.SCALEMODE_CEILING:
  8030. default:
  8031. pot = Tools.CeilingPOT(value);
  8032. break;
  8033. }
  8034. return Math.min(pot, max);
  8035. };
  8036. Tools.GetFilename = function (path) {
  8037. var index = path.lastIndexOf("/");
  8038. if (index < 0)
  8039. return path;
  8040. return path.substring(index + 1);
  8041. };
  8042. /**
  8043. * Extracts the "folder" part of a path (everything before the filename).
  8044. * @param uri The URI to extract the info from
  8045. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8046. * @returns The "folder" part of the path
  8047. */
  8048. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8049. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8050. var index = uri.lastIndexOf("/");
  8051. if (index < 0) {
  8052. if (returnUnchangedIfNoSlash) {
  8053. return uri;
  8054. }
  8055. return "";
  8056. }
  8057. return uri.substring(0, index + 1);
  8058. };
  8059. Tools.GetDOMTextContent = function (element) {
  8060. var result = "";
  8061. var child = element.firstChild;
  8062. while (child) {
  8063. if (child.nodeType === 3) {
  8064. result += child.textContent;
  8065. }
  8066. child = child.nextSibling;
  8067. }
  8068. return result;
  8069. };
  8070. Tools.ToDegrees = function (angle) {
  8071. return angle * 180 / Math.PI;
  8072. };
  8073. Tools.ToRadians = function (angle) {
  8074. return angle * Math.PI / 180;
  8075. };
  8076. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8077. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8078. var output = "";
  8079. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8080. var i = 0;
  8081. var bytes = new Uint8Array(buffer);
  8082. while (i < bytes.length) {
  8083. chr1 = bytes[i++];
  8084. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8085. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8086. enc1 = chr1 >> 2;
  8087. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8088. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8089. enc4 = chr3 & 63;
  8090. if (isNaN(chr2)) {
  8091. enc3 = enc4 = 64;
  8092. }
  8093. else if (isNaN(chr3)) {
  8094. enc4 = 64;
  8095. }
  8096. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8097. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8098. }
  8099. return "data:image/png;base64," + output;
  8100. };
  8101. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8102. if (bias === void 0) { bias = null; }
  8103. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8104. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8105. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8106. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8107. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8108. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8109. }
  8110. if (bias) {
  8111. minimum.x -= minimum.x * bias.x + bias.y;
  8112. minimum.y -= minimum.y * bias.x + bias.y;
  8113. minimum.z -= minimum.z * bias.x + bias.y;
  8114. maximum.x += maximum.x * bias.x + bias.y;
  8115. maximum.y += maximum.y * bias.x + bias.y;
  8116. maximum.z += maximum.z * bias.x + bias.y;
  8117. }
  8118. return {
  8119. minimum: minimum,
  8120. maximum: maximum
  8121. };
  8122. };
  8123. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8124. if (bias === void 0) { bias = null; }
  8125. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8126. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8127. if (!stride) {
  8128. stride = 3;
  8129. }
  8130. for (var index = start; index < start + count; index++) {
  8131. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8132. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8133. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8134. }
  8135. if (bias) {
  8136. minimum.x -= minimum.x * bias.x + bias.y;
  8137. minimum.y -= minimum.y * bias.x + bias.y;
  8138. minimum.z -= minimum.z * bias.x + bias.y;
  8139. maximum.x += maximum.x * bias.x + bias.y;
  8140. maximum.y += maximum.y * bias.x + bias.y;
  8141. maximum.z += maximum.z * bias.x + bias.y;
  8142. }
  8143. return {
  8144. minimum: minimum,
  8145. maximum: maximum
  8146. };
  8147. };
  8148. Tools.Vector2ArrayFeeder = function (array) {
  8149. return function (index) {
  8150. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8151. var length = isFloatArray ? array.length / 2 : array.length;
  8152. if (index >= length) {
  8153. return null;
  8154. }
  8155. if (isFloatArray) {
  8156. var fa = array;
  8157. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8158. }
  8159. var a = array;
  8160. return a[index];
  8161. };
  8162. };
  8163. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8164. if (bias === void 0) { bias = null; }
  8165. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8166. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8167. var i = 0;
  8168. var cur = feeder(i++);
  8169. while (cur) {
  8170. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8171. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8172. cur = feeder(i++);
  8173. }
  8174. if (bias) {
  8175. minimum.x -= minimum.x * bias.x + bias.y;
  8176. minimum.y -= minimum.y * bias.x + bias.y;
  8177. maximum.x += maximum.x * bias.x + bias.y;
  8178. maximum.y += maximum.y * bias.x + bias.y;
  8179. }
  8180. return {
  8181. minimum: minimum,
  8182. maximum: maximum
  8183. };
  8184. };
  8185. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8186. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8187. return null;
  8188. return Array.isArray(obj) ? obj : [obj];
  8189. };
  8190. // Misc.
  8191. Tools.GetPointerPrefix = function () {
  8192. var eventPrefix = "pointer";
  8193. // Check if pointer events are supported
  8194. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8195. eventPrefix = "mouse";
  8196. }
  8197. return eventPrefix;
  8198. };
  8199. /**
  8200. * @param func - the function to be called
  8201. * @param requester - the object that will request the next frame. Falls back to window.
  8202. */
  8203. Tools.QueueNewFrame = function (func, requester) {
  8204. if (!Tools.IsWindowObjectExist()) {
  8205. return setTimeout(func, 16);
  8206. }
  8207. if (!requester) {
  8208. requester = window;
  8209. }
  8210. if (requester.requestAnimationFrame) {
  8211. return requester.requestAnimationFrame(func);
  8212. }
  8213. else if (requester.msRequestAnimationFrame) {
  8214. return requester.msRequestAnimationFrame(func);
  8215. }
  8216. else if (requester.webkitRequestAnimationFrame) {
  8217. return requester.webkitRequestAnimationFrame(func);
  8218. }
  8219. else if (requester.mozRequestAnimationFrame) {
  8220. return requester.mozRequestAnimationFrame(func);
  8221. }
  8222. else if (requester.oRequestAnimationFrame) {
  8223. return requester.oRequestAnimationFrame(func);
  8224. }
  8225. else {
  8226. return window.setTimeout(func, 16);
  8227. }
  8228. };
  8229. Tools.RequestFullscreen = function (element) {
  8230. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8231. if (!requestFunction)
  8232. return;
  8233. requestFunction.call(element);
  8234. };
  8235. Tools.ExitFullscreen = function () {
  8236. if (document.exitFullscreen) {
  8237. document.exitFullscreen();
  8238. }
  8239. else if (document.mozCancelFullScreen) {
  8240. document.mozCancelFullScreen();
  8241. }
  8242. else if (document.webkitCancelFullScreen) {
  8243. document.webkitCancelFullScreen();
  8244. }
  8245. else if (document.msCancelFullScreen) {
  8246. document.msCancelFullScreen();
  8247. }
  8248. };
  8249. Tools.SetCorsBehavior = function (url, element) {
  8250. if (url && url.indexOf("data:") === 0) {
  8251. return;
  8252. }
  8253. if (Tools.CorsBehavior) {
  8254. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8255. element.crossOrigin = Tools.CorsBehavior;
  8256. }
  8257. else {
  8258. var result = Tools.CorsBehavior(url);
  8259. if (result) {
  8260. element.crossOrigin = result;
  8261. }
  8262. }
  8263. }
  8264. };
  8265. // External files
  8266. Tools.CleanUrl = function (url) {
  8267. url = url.replace(/#/mg, "%23");
  8268. return url;
  8269. };
  8270. Tools.LoadImage = function (url, onLoad, onError, database) {
  8271. if (url instanceof ArrayBuffer) {
  8272. url = Tools.EncodeArrayBufferTobase64(url);
  8273. }
  8274. url = Tools.CleanUrl(url);
  8275. url = Tools.PreprocessUrl(url);
  8276. var img = new Image();
  8277. Tools.SetCorsBehavior(url, img);
  8278. var loadHandler = function () {
  8279. img.removeEventListener("load", loadHandler);
  8280. img.removeEventListener("error", errorHandler);
  8281. onLoad(img);
  8282. };
  8283. var errorHandler = function (err) {
  8284. img.removeEventListener("load", loadHandler);
  8285. img.removeEventListener("error", errorHandler);
  8286. Tools.Error("Error while trying to load image: " + url);
  8287. if (onError) {
  8288. onError("Error while trying to load image: " + url, err);
  8289. }
  8290. };
  8291. img.addEventListener("load", loadHandler);
  8292. img.addEventListener("error", errorHandler);
  8293. var noIndexedDB = function () {
  8294. img.src = url;
  8295. };
  8296. var loadFromIndexedDB = function () {
  8297. if (database) {
  8298. database.loadImageFromDB(url, img);
  8299. }
  8300. };
  8301. //ANY database to do!
  8302. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8303. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8304. }
  8305. else {
  8306. if (url.indexOf("file:") !== -1) {
  8307. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8308. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8309. try {
  8310. var blobURL;
  8311. try {
  8312. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8313. }
  8314. catch (ex) {
  8315. // Chrome doesn't support oneTimeOnly parameter
  8316. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8317. }
  8318. img.src = blobURL;
  8319. }
  8320. catch (e) {
  8321. img.src = "";
  8322. }
  8323. return img;
  8324. }
  8325. }
  8326. noIndexedDB();
  8327. }
  8328. return img;
  8329. };
  8330. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8331. url = Tools.CleanUrl(url);
  8332. url = Tools.PreprocessUrl(url);
  8333. // If file and file input are set
  8334. if (url.indexOf("file:") !== -1) {
  8335. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8336. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8337. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8338. }
  8339. }
  8340. var loadUrl = Tools.BaseUrl + url;
  8341. var aborted = false;
  8342. var fileRequest = {
  8343. onCompleteObservable: new BABYLON.Observable(),
  8344. abort: function () { return aborted = true; },
  8345. };
  8346. var requestFile = function () {
  8347. var request = new XMLHttpRequest();
  8348. var retryHandle = null;
  8349. fileRequest.abort = function () {
  8350. aborted = true;
  8351. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8352. request.abort();
  8353. }
  8354. if (retryHandle !== null) {
  8355. clearTimeout(retryHandle);
  8356. retryHandle = null;
  8357. }
  8358. };
  8359. var retryLoop = function (retryIndex) {
  8360. request.open('GET', loadUrl, true);
  8361. if (useArrayBuffer) {
  8362. request.responseType = "arraybuffer";
  8363. }
  8364. if (onProgress) {
  8365. request.addEventListener("progress", onProgress);
  8366. }
  8367. var onLoadEnd = function () {
  8368. request.removeEventListener("loadend", onLoadEnd);
  8369. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8370. fileRequest.onCompleteObservable.clear();
  8371. };
  8372. request.addEventListener("loadend", onLoadEnd);
  8373. var onReadyStateChange = function () {
  8374. if (aborted) {
  8375. return;
  8376. }
  8377. // In case of undefined state in some browsers.
  8378. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8379. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8380. request.removeEventListener("readystatechange", onReadyStateChange);
  8381. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8382. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8383. return;
  8384. }
  8385. var retryStrategy = Tools.DefaultRetryStrategy;
  8386. if (retryStrategy) {
  8387. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8388. if (waitTime !== -1) {
  8389. // Prevent the request from completing for retry.
  8390. request.removeEventListener("loadend", onLoadEnd);
  8391. request = new XMLHttpRequest();
  8392. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8393. return;
  8394. }
  8395. }
  8396. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8397. if (onError) {
  8398. onError(request, e);
  8399. }
  8400. else {
  8401. throw e;
  8402. }
  8403. }
  8404. };
  8405. request.addEventListener("readystatechange", onReadyStateChange);
  8406. request.send();
  8407. };
  8408. retryLoop(0);
  8409. };
  8410. // Caching all files
  8411. if (database && database.enableSceneOffline) {
  8412. var noIndexedDB_1 = function () {
  8413. if (!aborted) {
  8414. requestFile();
  8415. }
  8416. };
  8417. var loadFromIndexedDB = function () {
  8418. // TODO: database needs to support aborting and should return a IFileRequest
  8419. if (aborted) {
  8420. return;
  8421. }
  8422. if (database) {
  8423. database.loadFileFromDB(url, function (data) {
  8424. if (!aborted) {
  8425. onSuccess(data);
  8426. }
  8427. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8428. }, onProgress ? function (event) {
  8429. if (!aborted) {
  8430. onProgress(event);
  8431. }
  8432. } : undefined, noIndexedDB_1, useArrayBuffer);
  8433. }
  8434. };
  8435. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8436. }
  8437. else {
  8438. requestFile();
  8439. }
  8440. return fileRequest;
  8441. };
  8442. /**
  8443. * Load a script (identified by an url). When the url returns, the
  8444. * content of this file is added into a new script element, attached to the DOM (body element)
  8445. */
  8446. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8447. var head = document.getElementsByTagName('head')[0];
  8448. var script = document.createElement('script');
  8449. script.type = 'text/javascript';
  8450. script.src = scriptUrl;
  8451. script.onload = function () {
  8452. if (onSuccess) {
  8453. onSuccess();
  8454. }
  8455. };
  8456. script.onerror = function (e) {
  8457. if (onError) {
  8458. onError("Unable to load script", e);
  8459. }
  8460. };
  8461. head.appendChild(script);
  8462. };
  8463. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8464. var reader = new FileReader();
  8465. var request = {
  8466. onCompleteObservable: new BABYLON.Observable(),
  8467. abort: function () { return reader.abort(); },
  8468. };
  8469. reader.onloadend = function (e) {
  8470. request.onCompleteObservable.notifyObservers(request);
  8471. };
  8472. reader.onload = function (e) {
  8473. //target doesn't have result from ts 1.3
  8474. callback(e.target['result']);
  8475. };
  8476. reader.onprogress = progressCallback;
  8477. reader.readAsDataURL(fileToLoad);
  8478. return request;
  8479. };
  8480. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8481. var reader = new FileReader();
  8482. var request = {
  8483. onCompleteObservable: new BABYLON.Observable(),
  8484. abort: function () { return reader.abort(); },
  8485. };
  8486. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8487. reader.onerror = function (e) {
  8488. Tools.Log("Error while reading file: " + fileToLoad.name);
  8489. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8490. };
  8491. reader.onload = function (e) {
  8492. //target doesn't have result from ts 1.3
  8493. callback(e.target['result']);
  8494. };
  8495. if (progressCallBack) {
  8496. reader.onprogress = progressCallBack;
  8497. }
  8498. if (!useArrayBuffer) {
  8499. // Asynchronous read
  8500. reader.readAsText(fileToLoad);
  8501. }
  8502. else {
  8503. reader.readAsArrayBuffer(fileToLoad);
  8504. }
  8505. return request;
  8506. };
  8507. //returns a downloadable url to a file content.
  8508. Tools.FileAsURL = function (content) {
  8509. var fileBlob = new Blob([content]);
  8510. var url = window.URL || window.webkitURL;
  8511. var link = url.createObjectURL(fileBlob);
  8512. return link;
  8513. };
  8514. // Misc.
  8515. Tools.Format = function (value, decimals) {
  8516. if (decimals === void 0) { decimals = 2; }
  8517. return value.toFixed(decimals);
  8518. };
  8519. Tools.CheckExtends = function (v, min, max) {
  8520. if (v.x < min.x)
  8521. min.x = v.x;
  8522. if (v.y < min.y)
  8523. min.y = v.y;
  8524. if (v.z < min.z)
  8525. min.z = v.z;
  8526. if (v.x > max.x)
  8527. max.x = v.x;
  8528. if (v.y > max.y)
  8529. max.y = v.y;
  8530. if (v.z > max.z)
  8531. max.z = v.z;
  8532. };
  8533. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8534. for (var prop in source) {
  8535. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8536. continue;
  8537. }
  8538. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8539. continue;
  8540. }
  8541. var sourceValue = source[prop];
  8542. var typeOfSourceValue = typeof sourceValue;
  8543. if (typeOfSourceValue === "function") {
  8544. continue;
  8545. }
  8546. if (typeOfSourceValue === "object") {
  8547. if (sourceValue instanceof Array) {
  8548. destination[prop] = [];
  8549. if (sourceValue.length > 0) {
  8550. if (typeof sourceValue[0] == "object") {
  8551. for (var index = 0; index < sourceValue.length; index++) {
  8552. var clonedValue = cloneValue(sourceValue[index], destination);
  8553. if (destination[prop].indexOf(clonedValue) === -1) {
  8554. destination[prop].push(clonedValue);
  8555. }
  8556. }
  8557. }
  8558. else {
  8559. destination[prop] = sourceValue.slice(0);
  8560. }
  8561. }
  8562. }
  8563. else {
  8564. destination[prop] = cloneValue(sourceValue, destination);
  8565. }
  8566. }
  8567. else {
  8568. destination[prop] = sourceValue;
  8569. }
  8570. }
  8571. };
  8572. Tools.IsEmpty = function (obj) {
  8573. for (var i in obj) {
  8574. if (obj.hasOwnProperty(i)) {
  8575. return false;
  8576. }
  8577. }
  8578. return true;
  8579. };
  8580. Tools.RegisterTopRootEvents = function (events) {
  8581. for (var index = 0; index < events.length; index++) {
  8582. var event = events[index];
  8583. window.addEventListener(event.name, event.handler, false);
  8584. try {
  8585. if (window.parent) {
  8586. window.parent.addEventListener(event.name, event.handler, false);
  8587. }
  8588. }
  8589. catch (e) {
  8590. // Silently fails...
  8591. }
  8592. }
  8593. };
  8594. Tools.UnregisterTopRootEvents = function (events) {
  8595. for (var index = 0; index < events.length; index++) {
  8596. var event = events[index];
  8597. window.removeEventListener(event.name, event.handler);
  8598. try {
  8599. if (window.parent) {
  8600. window.parent.removeEventListener(event.name, event.handler);
  8601. }
  8602. }
  8603. catch (e) {
  8604. // Silently fails...
  8605. }
  8606. }
  8607. };
  8608. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8609. if (mimeType === void 0) { mimeType = "image/png"; }
  8610. // Read the contents of the framebuffer
  8611. var numberOfChannelsByLine = width * 4;
  8612. var halfHeight = height / 2;
  8613. //Reading datas from WebGL
  8614. var data = engine.readPixels(0, 0, width, height);
  8615. //To flip image on Y axis.
  8616. for (var i = 0; i < halfHeight; i++) {
  8617. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8618. var currentCell = j + i * numberOfChannelsByLine;
  8619. var targetLine = height - i - 1;
  8620. var targetCell = j + targetLine * numberOfChannelsByLine;
  8621. var temp = data[currentCell];
  8622. data[currentCell] = data[targetCell];
  8623. data[targetCell] = temp;
  8624. }
  8625. }
  8626. // Create a 2D canvas to store the result
  8627. if (!screenshotCanvas) {
  8628. screenshotCanvas = document.createElement('canvas');
  8629. }
  8630. screenshotCanvas.width = width;
  8631. screenshotCanvas.height = height;
  8632. var context = screenshotCanvas.getContext('2d');
  8633. if (context) {
  8634. // Copy the pixels to a 2D canvas
  8635. var imageData = context.createImageData(width, height);
  8636. var castData = (imageData.data);
  8637. castData.set(data);
  8638. context.putImageData(imageData, 0, 0);
  8639. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8640. }
  8641. };
  8642. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8643. if (mimeType === void 0) { mimeType = "image/png"; }
  8644. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8645. if (successCallback) {
  8646. successCallback(base64Image);
  8647. }
  8648. else {
  8649. // We need HTMLCanvasElement.toBlob for HD screenshots
  8650. if (!screenshotCanvas.toBlob) {
  8651. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8652. screenshotCanvas.toBlob = function (callback, type, quality) {
  8653. var _this = this;
  8654. setTimeout(function () {
  8655. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8656. for (var i = 0; i < len; i++) {
  8657. arr[i] = binStr.charCodeAt(i);
  8658. }
  8659. callback(new Blob([arr], { type: type || 'image/png' }));
  8660. });
  8661. };
  8662. }
  8663. screenshotCanvas.toBlob(function (blob) {
  8664. var url = URL.createObjectURL(blob);
  8665. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8666. if (("download" in document.createElement("a"))) {
  8667. var a = window.document.createElement("a");
  8668. a.href = url;
  8669. if (fileName) {
  8670. a.setAttribute("download", fileName);
  8671. }
  8672. else {
  8673. var date = new Date();
  8674. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8675. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8676. }
  8677. window.document.body.appendChild(a);
  8678. a.addEventListener("click", function () {
  8679. if (a.parentElement) {
  8680. a.parentElement.removeChild(a);
  8681. }
  8682. });
  8683. a.click();
  8684. }
  8685. else {
  8686. var newWindow = window.open("");
  8687. if (!newWindow)
  8688. return;
  8689. var img = newWindow.document.createElement("img");
  8690. img.onload = function () {
  8691. // no longer need to read the blob so it's revoked
  8692. URL.revokeObjectURL(url);
  8693. };
  8694. img.src = url;
  8695. newWindow.document.body.appendChild(img);
  8696. }
  8697. });
  8698. }
  8699. };
  8700. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8701. if (mimeType === void 0) { mimeType = "image/png"; }
  8702. var width;
  8703. var height;
  8704. // If a precision value is specified
  8705. if (size.precision) {
  8706. width = Math.round(engine.getRenderWidth() * size.precision);
  8707. height = Math.round(width / engine.getAspectRatio(camera));
  8708. }
  8709. else if (size.width && size.height) {
  8710. width = size.width;
  8711. height = size.height;
  8712. }
  8713. else if (size.width && !size.height) {
  8714. width = size.width;
  8715. height = Math.round(width / engine.getAspectRatio(camera));
  8716. }
  8717. else if (size.height && !size.width) {
  8718. height = size.height;
  8719. width = Math.round(height * engine.getAspectRatio(camera));
  8720. }
  8721. else if (!isNaN(size)) {
  8722. height = size;
  8723. width = size;
  8724. }
  8725. else {
  8726. Tools.Error("Invalid 'size' parameter !");
  8727. return;
  8728. }
  8729. if (!screenshotCanvas) {
  8730. screenshotCanvas = document.createElement('canvas');
  8731. }
  8732. screenshotCanvas.width = width;
  8733. screenshotCanvas.height = height;
  8734. var renderContext = screenshotCanvas.getContext("2d");
  8735. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8736. var newWidth = width;
  8737. var newHeight = newWidth / ratio;
  8738. if (newHeight > height) {
  8739. newHeight = height;
  8740. newWidth = newHeight * ratio;
  8741. }
  8742. var offsetX = Math.max(0, width - newWidth) / 2;
  8743. var offsetY = Math.max(0, height - newHeight) / 2;
  8744. var renderingCanvas = engine.getRenderingCanvas();
  8745. if (renderContext && renderingCanvas) {
  8746. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8747. }
  8748. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8749. };
  8750. /**
  8751. * Generates an image screenshot from the specified camera.
  8752. *
  8753. * @param engine The engine to use for rendering
  8754. * @param camera The camera to use for rendering
  8755. * @param size This parameter can be set to a single number or to an object with the
  8756. * following (optional) properties: precision, width, height. If a single number is passed,
  8757. * it will be used for both width and height. If an object is passed, the screenshot size
  8758. * will be derived from the parameters. The precision property is a multiplier allowing
  8759. * rendering at a higher or lower resolution.
  8760. * @param successCallback The callback receives a single parameter which contains the
  8761. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8762. * src parameter of an <img> to display it.
  8763. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8764. * Check your browser for supported MIME types.
  8765. * @param samples Texture samples (default: 1)
  8766. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8767. * @param fileName A name for for the downloaded file.
  8768. * @constructor
  8769. */
  8770. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8771. if (mimeType === void 0) { mimeType = "image/png"; }
  8772. if (samples === void 0) { samples = 1; }
  8773. if (antialiasing === void 0) { antialiasing = false; }
  8774. var width;
  8775. var height;
  8776. //If a precision value is specified
  8777. if (size.precision) {
  8778. width = Math.round(engine.getRenderWidth() * size.precision);
  8779. height = Math.round(width / engine.getAspectRatio(camera));
  8780. size = { width: width, height: height };
  8781. }
  8782. else if (size.width && size.height) {
  8783. width = size.width;
  8784. height = size.height;
  8785. }
  8786. else if (size.width && !size.height) {
  8787. width = size.width;
  8788. height = Math.round(width / engine.getAspectRatio(camera));
  8789. size = { width: width, height: height };
  8790. }
  8791. else if (size.height && !size.width) {
  8792. height = size.height;
  8793. width = Math.round(height * engine.getAspectRatio(camera));
  8794. size = { width: width, height: height };
  8795. }
  8796. else if (!isNaN(size)) {
  8797. height = size;
  8798. width = size;
  8799. }
  8800. else {
  8801. Tools.Error("Invalid 'size' parameter !");
  8802. return;
  8803. }
  8804. var scene = camera.getScene();
  8805. var previousCamera = null;
  8806. if (scene.activeCamera !== camera) {
  8807. previousCamera = scene.activeCamera;
  8808. scene.activeCamera = camera;
  8809. }
  8810. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8811. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8812. texture.renderList = null;
  8813. texture.samples = samples;
  8814. if (antialiasing) {
  8815. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8816. }
  8817. texture.onAfterRenderObservable.add(function () {
  8818. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8819. });
  8820. scene.incrementRenderId();
  8821. scene.resetCachedMaterial();
  8822. texture.render(true);
  8823. texture.dispose();
  8824. if (previousCamera) {
  8825. scene.activeCamera = previousCamera;
  8826. }
  8827. camera.getProjectionMatrix(true); // Force cache refresh;
  8828. };
  8829. // XHR response validator for local file scenario
  8830. Tools.ValidateXHRData = function (xhr, dataType) {
  8831. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8832. if (dataType === void 0) { dataType = 7; }
  8833. try {
  8834. if (dataType & 1) {
  8835. if (xhr.responseText && xhr.responseText.length > 0) {
  8836. return true;
  8837. }
  8838. else if (dataType === 1) {
  8839. return false;
  8840. }
  8841. }
  8842. if (dataType & 2) {
  8843. // Check header width and height since there is no "TGA" magic number
  8844. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8845. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8846. return true;
  8847. }
  8848. else if (dataType === 2) {
  8849. return false;
  8850. }
  8851. }
  8852. if (dataType & 4) {
  8853. // Check for the "DDS" magic number
  8854. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8855. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8856. return true;
  8857. }
  8858. else {
  8859. return false;
  8860. }
  8861. }
  8862. }
  8863. catch (e) {
  8864. // Global protection
  8865. }
  8866. return false;
  8867. };
  8868. /**
  8869. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8870. * Be aware Math.random() could cause collisions, but:
  8871. * "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"
  8872. */
  8873. Tools.RandomId = function () {
  8874. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8875. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8876. return v.toString(16);
  8877. });
  8878. };
  8879. /**
  8880. * Test if the given uri is a base64 string.
  8881. * @param uri The uri to test
  8882. * @return True if the uri is a base64 string or false otherwise.
  8883. */
  8884. Tools.IsBase64 = function (uri) {
  8885. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8886. };
  8887. /**
  8888. * Decode the given base64 uri.
  8889. * @param uri The uri to decode
  8890. * @return The decoded base64 data.
  8891. */
  8892. Tools.DecodeBase64 = function (uri) {
  8893. var decodedString = atob(uri.split(",")[1]);
  8894. var bufferLength = decodedString.length;
  8895. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8896. for (var i = 0; i < bufferLength; i++) {
  8897. bufferView[i] = decodedString.charCodeAt(i);
  8898. }
  8899. return bufferView.buffer;
  8900. };
  8901. Object.defineProperty(Tools, "NoneLogLevel", {
  8902. get: function () {
  8903. return Tools._NoneLogLevel;
  8904. },
  8905. enumerable: true,
  8906. configurable: true
  8907. });
  8908. Object.defineProperty(Tools, "MessageLogLevel", {
  8909. get: function () {
  8910. return Tools._MessageLogLevel;
  8911. },
  8912. enumerable: true,
  8913. configurable: true
  8914. });
  8915. Object.defineProperty(Tools, "WarningLogLevel", {
  8916. get: function () {
  8917. return Tools._WarningLogLevel;
  8918. },
  8919. enumerable: true,
  8920. configurable: true
  8921. });
  8922. Object.defineProperty(Tools, "ErrorLogLevel", {
  8923. get: function () {
  8924. return Tools._ErrorLogLevel;
  8925. },
  8926. enumerable: true,
  8927. configurable: true
  8928. });
  8929. Object.defineProperty(Tools, "AllLogLevel", {
  8930. get: function () {
  8931. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8932. },
  8933. enumerable: true,
  8934. configurable: true
  8935. });
  8936. Tools._AddLogEntry = function (entry) {
  8937. Tools._LogCache = entry + Tools._LogCache;
  8938. if (Tools.OnNewCacheEntry) {
  8939. Tools.OnNewCacheEntry(entry);
  8940. }
  8941. };
  8942. Tools._FormatMessage = function (message) {
  8943. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8944. var date = new Date();
  8945. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8946. };
  8947. Tools._LogDisabled = function (message) {
  8948. // nothing to do
  8949. };
  8950. Tools._LogEnabled = function (message) {
  8951. var formattedMessage = Tools._FormatMessage(message);
  8952. console.log("BJS - " + formattedMessage);
  8953. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8954. Tools._AddLogEntry(entry);
  8955. };
  8956. Tools._WarnDisabled = function (message) {
  8957. // nothing to do
  8958. };
  8959. Tools._WarnEnabled = function (message) {
  8960. var formattedMessage = Tools._FormatMessage(message);
  8961. console.warn("BJS - " + formattedMessage);
  8962. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8963. Tools._AddLogEntry(entry);
  8964. };
  8965. Tools._ErrorDisabled = function (message) {
  8966. // nothing to do
  8967. };
  8968. Tools._ErrorEnabled = function (message) {
  8969. Tools.errorsCount++;
  8970. var formattedMessage = Tools._FormatMessage(message);
  8971. console.error("BJS - " + formattedMessage);
  8972. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8973. Tools._AddLogEntry(entry);
  8974. };
  8975. Object.defineProperty(Tools, "LogCache", {
  8976. get: function () {
  8977. return Tools._LogCache;
  8978. },
  8979. enumerable: true,
  8980. configurable: true
  8981. });
  8982. Tools.ClearLogCache = function () {
  8983. Tools._LogCache = "";
  8984. Tools.errorsCount = 0;
  8985. };
  8986. Object.defineProperty(Tools, "LogLevels", {
  8987. set: function (level) {
  8988. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8989. Tools.Log = Tools._LogEnabled;
  8990. }
  8991. else {
  8992. Tools.Log = Tools._LogDisabled;
  8993. }
  8994. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8995. Tools.Warn = Tools._WarnEnabled;
  8996. }
  8997. else {
  8998. Tools.Warn = Tools._WarnDisabled;
  8999. }
  9000. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9001. Tools.Error = Tools._ErrorEnabled;
  9002. }
  9003. else {
  9004. Tools.Error = Tools._ErrorDisabled;
  9005. }
  9006. },
  9007. enumerable: true,
  9008. configurable: true
  9009. });
  9010. Tools.IsWindowObjectExist = function () {
  9011. return (typeof window) !== "undefined";
  9012. };
  9013. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9014. get: function () {
  9015. return Tools._PerformanceNoneLogLevel;
  9016. },
  9017. enumerable: true,
  9018. configurable: true
  9019. });
  9020. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9021. get: function () {
  9022. return Tools._PerformanceUserMarkLogLevel;
  9023. },
  9024. enumerable: true,
  9025. configurable: true
  9026. });
  9027. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9028. get: function () {
  9029. return Tools._PerformanceConsoleLogLevel;
  9030. },
  9031. enumerable: true,
  9032. configurable: true
  9033. });
  9034. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9035. set: function (level) {
  9036. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9037. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9038. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9039. return;
  9040. }
  9041. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9042. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9043. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9044. return;
  9045. }
  9046. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9047. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9048. },
  9049. enumerable: true,
  9050. configurable: true
  9051. });
  9052. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9053. };
  9054. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9055. };
  9056. Tools._StartUserMark = function (counterName, condition) {
  9057. if (condition === void 0) { condition = true; }
  9058. if (!Tools._performance) {
  9059. if (!Tools.IsWindowObjectExist()) {
  9060. return;
  9061. }
  9062. Tools._performance = window.performance;
  9063. }
  9064. if (!condition || !Tools._performance.mark) {
  9065. return;
  9066. }
  9067. Tools._performance.mark(counterName + "-Begin");
  9068. };
  9069. Tools._EndUserMark = function (counterName, condition) {
  9070. if (condition === void 0) { condition = true; }
  9071. if (!condition || !Tools._performance.mark) {
  9072. return;
  9073. }
  9074. Tools._performance.mark(counterName + "-End");
  9075. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9076. };
  9077. Tools._StartPerformanceConsole = function (counterName, condition) {
  9078. if (condition === void 0) { condition = true; }
  9079. if (!condition) {
  9080. return;
  9081. }
  9082. Tools._StartUserMark(counterName, condition);
  9083. if (console.time) {
  9084. console.time(counterName);
  9085. }
  9086. };
  9087. Tools._EndPerformanceConsole = function (counterName, condition) {
  9088. if (condition === void 0) { condition = true; }
  9089. if (!condition) {
  9090. return;
  9091. }
  9092. Tools._EndUserMark(counterName, condition);
  9093. if (console.time) {
  9094. console.timeEnd(counterName);
  9095. }
  9096. };
  9097. Object.defineProperty(Tools, "Now", {
  9098. get: function () {
  9099. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9100. return window.performance.now();
  9101. }
  9102. return new Date().getTime();
  9103. },
  9104. enumerable: true,
  9105. configurable: true
  9106. });
  9107. /**
  9108. * This method will return the name of the class used to create the instance of the given object.
  9109. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9110. * @param object the object to get the class name from
  9111. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9112. */
  9113. Tools.GetClassName = function (object, isType) {
  9114. if (isType === void 0) { isType = false; }
  9115. var name = null;
  9116. if (!isType && object.getClassName) {
  9117. name = object.getClassName();
  9118. }
  9119. else {
  9120. if (object instanceof Object) {
  9121. var classObj = isType ? object : Object.getPrototypeOf(object);
  9122. name = classObj.constructor["__bjsclassName__"];
  9123. }
  9124. if (!name) {
  9125. name = typeof object;
  9126. }
  9127. }
  9128. return name;
  9129. };
  9130. Tools.First = function (array, predicate) {
  9131. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9132. var el = array_1[_i];
  9133. if (predicate(el)) {
  9134. return el;
  9135. }
  9136. }
  9137. return null;
  9138. };
  9139. /**
  9140. * This method will return the name of the full name of the class, including its owning module (if any).
  9141. * 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).
  9142. * @param object the object to get the class name from
  9143. * @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.
  9144. */
  9145. Tools.getFullClassName = function (object, isType) {
  9146. if (isType === void 0) { isType = false; }
  9147. var className = null;
  9148. var moduleName = null;
  9149. if (!isType && object.getClassName) {
  9150. className = object.getClassName();
  9151. }
  9152. else {
  9153. if (object instanceof Object) {
  9154. var classObj = isType ? object : Object.getPrototypeOf(object);
  9155. className = classObj.constructor["__bjsclassName__"];
  9156. moduleName = classObj.constructor["__bjsmoduleName__"];
  9157. }
  9158. if (!className) {
  9159. className = typeof object;
  9160. }
  9161. }
  9162. if (!className) {
  9163. return null;
  9164. }
  9165. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9166. };
  9167. /**
  9168. * 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.
  9169. * @param array
  9170. */
  9171. Tools.arrayOrStringFeeder = function (array) {
  9172. return function (index) {
  9173. if (index >= array.length) {
  9174. return null;
  9175. }
  9176. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9177. if (val && val.getHashCode) {
  9178. val = val.getHashCode();
  9179. }
  9180. if (typeof val === "string") {
  9181. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9182. }
  9183. return val;
  9184. };
  9185. };
  9186. /**
  9187. * Compute the hashCode of a stream of number
  9188. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9189. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9190. * @return the hash code computed
  9191. */
  9192. Tools.hashCodeFromStream = function (feeder) {
  9193. // Based from here: http://stackoverflow.com/a/7616484/802124
  9194. var hash = 0;
  9195. var index = 0;
  9196. var chr = feeder(index++);
  9197. while (chr != null) {
  9198. hash = ((hash << 5) - hash) + chr;
  9199. hash |= 0; // Convert to 32bit integer
  9200. chr = feeder(index++);
  9201. }
  9202. return hash;
  9203. };
  9204. /**
  9205. * Returns a promise that resolves after the given amount of time.
  9206. * @param delay Number of milliseconds to delay
  9207. * @returns Promise that resolves after the given amount of time
  9208. */
  9209. Tools.DelayAsync = function (delay) {
  9210. return new Promise(function (resolve) {
  9211. setTimeout(function () {
  9212. resolve();
  9213. }, delay);
  9214. });
  9215. };
  9216. Tools.BaseUrl = "";
  9217. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9218. /**
  9219. * Default behaviour for cors in the application.
  9220. * It can be a string if the expected behavior is identical in the entire app.
  9221. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9222. */
  9223. Tools.CorsBehavior = "anonymous";
  9224. Tools.UseFallbackTexture = true;
  9225. /**
  9226. * Use this object to register external classes like custom textures or material
  9227. * to allow the laoders to instantiate them
  9228. */
  9229. Tools.RegisteredExternalClasses = {};
  9230. // Used in case of a texture loading problem
  9231. 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";
  9232. Tools.PreprocessUrl = function (url) {
  9233. return url;
  9234. };
  9235. // Logs
  9236. Tools._NoneLogLevel = 0;
  9237. Tools._MessageLogLevel = 1;
  9238. Tools._WarningLogLevel = 2;
  9239. Tools._ErrorLogLevel = 4;
  9240. Tools._LogCache = "";
  9241. Tools.errorsCount = 0;
  9242. Tools.Log = Tools._LogEnabled;
  9243. Tools.Warn = Tools._WarnEnabled;
  9244. Tools.Error = Tools._ErrorEnabled;
  9245. // Performances
  9246. Tools._PerformanceNoneLogLevel = 0;
  9247. Tools._PerformanceUserMarkLogLevel = 1;
  9248. Tools._PerformanceConsoleLogLevel = 2;
  9249. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9250. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9251. return Tools;
  9252. }());
  9253. BABYLON.Tools = Tools;
  9254. /**
  9255. * This class is used to track a performance counter which is number based.
  9256. * The user has access to many properties which give statistics of different nature
  9257. *
  9258. * The implementer can track two kinds of Performance Counter: time and count
  9259. * 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.
  9260. * 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.
  9261. */
  9262. var PerfCounter = /** @class */ (function () {
  9263. function PerfCounter() {
  9264. this._startMonitoringTime = 0;
  9265. this._min = 0;
  9266. this._max = 0;
  9267. this._average = 0;
  9268. this._lastSecAverage = 0;
  9269. this._current = 0;
  9270. this._totalValueCount = 0;
  9271. this._totalAccumulated = 0;
  9272. this._lastSecAccumulated = 0;
  9273. this._lastSecTime = 0;
  9274. this._lastSecValueCount = 0;
  9275. }
  9276. Object.defineProperty(PerfCounter.prototype, "min", {
  9277. /**
  9278. * Returns the smallest value ever
  9279. */
  9280. get: function () {
  9281. return this._min;
  9282. },
  9283. enumerable: true,
  9284. configurable: true
  9285. });
  9286. Object.defineProperty(PerfCounter.prototype, "max", {
  9287. /**
  9288. * Returns the biggest value ever
  9289. */
  9290. get: function () {
  9291. return this._max;
  9292. },
  9293. enumerable: true,
  9294. configurable: true
  9295. });
  9296. Object.defineProperty(PerfCounter.prototype, "average", {
  9297. /**
  9298. * Returns the average value since the performance counter is running
  9299. */
  9300. get: function () {
  9301. return this._average;
  9302. },
  9303. enumerable: true,
  9304. configurable: true
  9305. });
  9306. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9307. /**
  9308. * Returns the average value of the last second the counter was monitored
  9309. */
  9310. get: function () {
  9311. return this._lastSecAverage;
  9312. },
  9313. enumerable: true,
  9314. configurable: true
  9315. });
  9316. Object.defineProperty(PerfCounter.prototype, "current", {
  9317. /**
  9318. * Returns the current value
  9319. */
  9320. get: function () {
  9321. return this._current;
  9322. },
  9323. enumerable: true,
  9324. configurable: true
  9325. });
  9326. Object.defineProperty(PerfCounter.prototype, "total", {
  9327. get: function () {
  9328. return this._totalAccumulated;
  9329. },
  9330. enumerable: true,
  9331. configurable: true
  9332. });
  9333. Object.defineProperty(PerfCounter.prototype, "count", {
  9334. get: function () {
  9335. return this._totalValueCount;
  9336. },
  9337. enumerable: true,
  9338. configurable: true
  9339. });
  9340. /**
  9341. * Call this method to start monitoring a new frame.
  9342. * 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.
  9343. */
  9344. PerfCounter.prototype.fetchNewFrame = function () {
  9345. this._totalValueCount++;
  9346. this._current = 0;
  9347. this._lastSecValueCount++;
  9348. };
  9349. /**
  9350. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9351. * @param newCount the count value to add to the monitored count
  9352. * @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.
  9353. */
  9354. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9355. if (!PerfCounter.Enabled) {
  9356. return;
  9357. }
  9358. this._current += newCount;
  9359. if (fetchResult) {
  9360. this._fetchResult();
  9361. }
  9362. };
  9363. /**
  9364. * Start monitoring this performance counter
  9365. */
  9366. PerfCounter.prototype.beginMonitoring = function () {
  9367. if (!PerfCounter.Enabled) {
  9368. return;
  9369. }
  9370. this._startMonitoringTime = Tools.Now;
  9371. };
  9372. /**
  9373. * Compute the time lapsed since the previous beginMonitoring() call.
  9374. * @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
  9375. */
  9376. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9377. if (newFrame === void 0) { newFrame = true; }
  9378. if (!PerfCounter.Enabled) {
  9379. return;
  9380. }
  9381. if (newFrame) {
  9382. this.fetchNewFrame();
  9383. }
  9384. var currentTime = Tools.Now;
  9385. this._current = currentTime - this._startMonitoringTime;
  9386. if (newFrame) {
  9387. this._fetchResult();
  9388. }
  9389. };
  9390. PerfCounter.prototype._fetchResult = function () {
  9391. this._totalAccumulated += this._current;
  9392. this._lastSecAccumulated += this._current;
  9393. // Min/Max update
  9394. this._min = Math.min(this._min, this._current);
  9395. this._max = Math.max(this._max, this._current);
  9396. this._average = this._totalAccumulated / this._totalValueCount;
  9397. // Reset last sec?
  9398. var now = Tools.Now;
  9399. if ((now - this._lastSecTime) > 1000) {
  9400. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9401. this._lastSecTime = now;
  9402. this._lastSecAccumulated = 0;
  9403. this._lastSecValueCount = 0;
  9404. }
  9405. };
  9406. PerfCounter.Enabled = true;
  9407. return PerfCounter;
  9408. }());
  9409. BABYLON.PerfCounter = PerfCounter;
  9410. /**
  9411. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9412. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9413. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9414. * @param name The name of the class, case should be preserved
  9415. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9416. */
  9417. function className(name, module) {
  9418. return function (target) {
  9419. target["__bjsclassName__"] = name;
  9420. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9421. };
  9422. }
  9423. BABYLON.className = className;
  9424. /**
  9425. * An implementation of a loop for asynchronous functions.
  9426. */
  9427. var AsyncLoop = /** @class */ (function () {
  9428. /**
  9429. * Constroctor.
  9430. * @param iterations the number of iterations.
  9431. * @param _fn the function to run each iteration
  9432. * @param _successCallback the callback that will be called upon succesful execution
  9433. * @param offset starting offset.
  9434. */
  9435. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9436. if (offset === void 0) { offset = 0; }
  9437. this.iterations = iterations;
  9438. this._fn = _fn;
  9439. this._successCallback = _successCallback;
  9440. this.index = offset - 1;
  9441. this._done = false;
  9442. }
  9443. /**
  9444. * Execute the next iteration. Must be called after the last iteration was finished.
  9445. */
  9446. AsyncLoop.prototype.executeNext = function () {
  9447. if (!this._done) {
  9448. if (this.index + 1 < this.iterations) {
  9449. ++this.index;
  9450. this._fn(this);
  9451. }
  9452. else {
  9453. this.breakLoop();
  9454. }
  9455. }
  9456. };
  9457. /**
  9458. * Break the loop and run the success callback.
  9459. */
  9460. AsyncLoop.prototype.breakLoop = function () {
  9461. this._done = true;
  9462. this._successCallback();
  9463. };
  9464. /**
  9465. * Helper function
  9466. */
  9467. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9468. if (offset === void 0) { offset = 0; }
  9469. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9470. loop.executeNext();
  9471. return loop;
  9472. };
  9473. /**
  9474. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9475. * @param iterations total number of iterations
  9476. * @param syncedIterations number of synchronous iterations in each async iteration.
  9477. * @param fn the function to call each iteration.
  9478. * @param callback a success call back that will be called when iterating stops.
  9479. * @param breakFunction a break condition (optional)
  9480. * @param timeout timeout settings for the setTimeout function. default - 0.
  9481. * @constructor
  9482. */
  9483. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9484. if (timeout === void 0) { timeout = 0; }
  9485. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9486. if (breakFunction && breakFunction())
  9487. loop.breakLoop();
  9488. else {
  9489. setTimeout(function () {
  9490. for (var i = 0; i < syncedIterations; ++i) {
  9491. var iteration = (loop.index * syncedIterations) + i;
  9492. if (iteration >= iterations)
  9493. break;
  9494. fn(iteration);
  9495. if (breakFunction && breakFunction()) {
  9496. loop.breakLoop();
  9497. break;
  9498. }
  9499. }
  9500. loop.executeNext();
  9501. }, timeout);
  9502. }
  9503. }, callback);
  9504. };
  9505. return AsyncLoop;
  9506. }());
  9507. BABYLON.AsyncLoop = AsyncLoop;
  9508. })(BABYLON || (BABYLON = {}));
  9509. //# sourceMappingURL=babylon.tools.js.map
  9510. var BABYLON;
  9511. (function (BABYLON) {
  9512. var PromiseStates;
  9513. (function (PromiseStates) {
  9514. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9515. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9516. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9517. })(PromiseStates || (PromiseStates = {}));
  9518. var FulFillmentAgregator = /** @class */ (function () {
  9519. function FulFillmentAgregator() {
  9520. this.count = 0;
  9521. this.target = 0;
  9522. this.results = [];
  9523. }
  9524. return FulFillmentAgregator;
  9525. }());
  9526. var InternalPromise = /** @class */ (function () {
  9527. function InternalPromise(resolver) {
  9528. var _this = this;
  9529. this._state = PromiseStates.Pending;
  9530. this._children = new Array();
  9531. this._rejectWasConsumed = false;
  9532. if (!resolver) {
  9533. return;
  9534. }
  9535. try {
  9536. resolver(function (value) {
  9537. _this._resolve(value);
  9538. }, function (reason) {
  9539. _this._reject(reason);
  9540. });
  9541. }
  9542. catch (e) {
  9543. this._reject(e);
  9544. }
  9545. }
  9546. InternalPromise.prototype.catch = function (onRejected) {
  9547. return this.then(undefined, onRejected);
  9548. };
  9549. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9550. var _this = this;
  9551. var newPromise = new InternalPromise();
  9552. newPromise._onFulfilled = onFulfilled;
  9553. newPromise._onRejected = onRejected;
  9554. // Composition
  9555. this._children.push(newPromise);
  9556. if (this._state !== PromiseStates.Pending) {
  9557. BABYLON.Tools.SetImmediate(function () {
  9558. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9559. var returnedValue = newPromise._resolve(_this._result);
  9560. if (returnedValue !== undefined && returnedValue !== null) {
  9561. if (returnedValue._state !== undefined) {
  9562. var returnedPromise = returnedValue;
  9563. newPromise._children.push(returnedPromise);
  9564. newPromise = returnedPromise;
  9565. }
  9566. else {
  9567. newPromise._result = returnedValue;
  9568. }
  9569. }
  9570. }
  9571. else {
  9572. newPromise._reject(_this._reason);
  9573. }
  9574. });
  9575. }
  9576. return newPromise;
  9577. };
  9578. InternalPromise.prototype._moveChildren = function (children) {
  9579. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9580. if (this._state === PromiseStates.Fulfilled) {
  9581. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9582. var child = _b[_i];
  9583. child._resolve(this._result);
  9584. }
  9585. }
  9586. else if (this._state === PromiseStates.Rejected) {
  9587. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9588. var child = _d[_c];
  9589. child._reject(this._reason);
  9590. }
  9591. }
  9592. var _a;
  9593. };
  9594. InternalPromise.prototype._resolve = function (value) {
  9595. try {
  9596. this._state = PromiseStates.Fulfilled;
  9597. this._result = value;
  9598. var returnedValue = null;
  9599. if (this._onFulfilled) {
  9600. returnedValue = this._onFulfilled(value);
  9601. }
  9602. if (returnedValue !== undefined && returnedValue !== null) {
  9603. if (returnedValue._state !== undefined) {
  9604. // Transmit children
  9605. var returnedPromise = returnedValue;
  9606. returnedPromise._moveChildren(this._children);
  9607. }
  9608. else {
  9609. value = returnedValue;
  9610. }
  9611. }
  9612. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9613. var child = _a[_i];
  9614. child._resolve(value);
  9615. }
  9616. this._children.length = 0;
  9617. delete this._onFulfilled;
  9618. delete this._onRejected;
  9619. return returnedValue;
  9620. }
  9621. catch (e) {
  9622. this._reject(e, true);
  9623. }
  9624. return null;
  9625. };
  9626. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9627. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9628. this._state = PromiseStates.Rejected;
  9629. this._reason = reason;
  9630. if (this._onRejected && !onLocalThrow) {
  9631. try {
  9632. this._onRejected(reason);
  9633. this._rejectWasConsumed = true;
  9634. }
  9635. catch (e) {
  9636. reason = e;
  9637. }
  9638. }
  9639. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9640. var child = _a[_i];
  9641. if (this._rejectWasConsumed) {
  9642. child._resolve(null);
  9643. }
  9644. else {
  9645. child._reject(reason);
  9646. }
  9647. }
  9648. this._children.length = 0;
  9649. delete this._onFulfilled;
  9650. delete this._onRejected;
  9651. };
  9652. InternalPromise.resolve = function (value) {
  9653. var newPromise = new InternalPromise();
  9654. newPromise._resolve(value);
  9655. return newPromise;
  9656. };
  9657. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9658. promise.then(function (value) {
  9659. agregator.results[index] = value;
  9660. agregator.count++;
  9661. if (agregator.count === agregator.target) {
  9662. agregator.rootPromise._resolve(agregator.results);
  9663. }
  9664. return null;
  9665. }, function (reason) {
  9666. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9667. agregator.rootPromise._reject(reason);
  9668. }
  9669. });
  9670. };
  9671. InternalPromise.all = function (promises) {
  9672. var newPromise = new InternalPromise();
  9673. var agregator = new FulFillmentAgregator();
  9674. agregator.target = promises.length;
  9675. agregator.rootPromise = newPromise;
  9676. if (promises.length) {
  9677. for (var index = 0; index < promises.length; index++) {
  9678. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9679. }
  9680. }
  9681. else {
  9682. newPromise._resolve([]);
  9683. }
  9684. return newPromise;
  9685. };
  9686. InternalPromise.race = function (promises) {
  9687. var newPromise = new InternalPromise();
  9688. if (promises.length) {
  9689. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9690. var promise = promises_1[_i];
  9691. promise.then(function (value) {
  9692. if (newPromise) {
  9693. newPromise._resolve(value);
  9694. newPromise = null;
  9695. }
  9696. return null;
  9697. }, function (reason) {
  9698. if (newPromise) {
  9699. newPromise._reject(reason);
  9700. newPromise = null;
  9701. }
  9702. });
  9703. }
  9704. }
  9705. return newPromise;
  9706. };
  9707. return InternalPromise;
  9708. }());
  9709. /**
  9710. * Helper class that provides a small promise polyfill
  9711. */
  9712. var PromisePolyfill = /** @class */ (function () {
  9713. function PromisePolyfill() {
  9714. }
  9715. /**
  9716. * Static function used to check if the polyfill is required
  9717. * If this is the case then the function will inject the polyfill to window.Promise
  9718. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9719. */
  9720. PromisePolyfill.Apply = function (force) {
  9721. if (force === void 0) { force = false; }
  9722. if (force || typeof Promise === 'undefined') {
  9723. var root = window;
  9724. root.Promise = InternalPromise;
  9725. }
  9726. };
  9727. return PromisePolyfill;
  9728. }());
  9729. BABYLON.PromisePolyfill = PromisePolyfill;
  9730. })(BABYLON || (BABYLON = {}));
  9731. //# sourceMappingURL=babylon.promise.js.map
  9732. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9733. var BABYLON;
  9734. (function (BABYLON) {
  9735. /**
  9736. * Helper class to push actions to a pool of workers.
  9737. */
  9738. var WorkerPool = /** @class */ (function () {
  9739. /**
  9740. * Constructor
  9741. * @param workers Array of workers to use for actions
  9742. */
  9743. function WorkerPool(workers) {
  9744. this._pendingActions = new Array();
  9745. this._workerInfos = workers.map(function (worker) { return ({
  9746. worker: worker,
  9747. active: false
  9748. }); });
  9749. }
  9750. /**
  9751. * Terminates all workers and clears any pending actions.
  9752. */
  9753. WorkerPool.prototype.dispose = function () {
  9754. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9755. var workerInfo = _a[_i];
  9756. workerInfo.worker.terminate();
  9757. }
  9758. delete this._workerInfos;
  9759. delete this._pendingActions;
  9760. };
  9761. /**
  9762. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9763. * pended until a worker has completed its action.
  9764. * @param action The action to perform. Call onComplete when the action is complete.
  9765. */
  9766. WorkerPool.prototype.push = function (action) {
  9767. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9768. var workerInfo = _a[_i];
  9769. if (!workerInfo.active) {
  9770. this._execute(workerInfo, action);
  9771. return;
  9772. }
  9773. }
  9774. this._pendingActions.push(action);
  9775. };
  9776. WorkerPool.prototype._execute = function (workerInfo, action) {
  9777. var _this = this;
  9778. workerInfo.active = true;
  9779. action(workerInfo.worker, function () {
  9780. workerInfo.active = false;
  9781. var nextAction = _this._pendingActions.shift();
  9782. if (nextAction) {
  9783. _this._execute(workerInfo, nextAction);
  9784. }
  9785. });
  9786. };
  9787. return WorkerPool;
  9788. }());
  9789. BABYLON.WorkerPool = WorkerPool;
  9790. })(BABYLON || (BABYLON = {}));
  9791. //# sourceMappingURL=babylon.workerPool.js.map
  9792. var BABYLON;
  9793. (function (BABYLON) {
  9794. var _AlphaState = /** @class */ (function () {
  9795. /**
  9796. * Initializes the state.
  9797. */
  9798. function _AlphaState() {
  9799. this._isAlphaBlendDirty = false;
  9800. this._isBlendFunctionParametersDirty = false;
  9801. this._isBlendEquationParametersDirty = false;
  9802. this._isBlendConstantsDirty = false;
  9803. this._alphaBlend = false;
  9804. this._blendFunctionParameters = new Array(4);
  9805. this._blendEquationParameters = new Array(2);
  9806. this._blendConstants = new Array(4);
  9807. this.reset();
  9808. }
  9809. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9810. get: function () {
  9811. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9812. },
  9813. enumerable: true,
  9814. configurable: true
  9815. });
  9816. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9817. get: function () {
  9818. return this._alphaBlend;
  9819. },
  9820. set: function (value) {
  9821. if (this._alphaBlend === value) {
  9822. return;
  9823. }
  9824. this._alphaBlend = value;
  9825. this._isAlphaBlendDirty = true;
  9826. },
  9827. enumerable: true,
  9828. configurable: true
  9829. });
  9830. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9831. if (this._blendConstants[0] === r &&
  9832. this._blendConstants[1] === g &&
  9833. this._blendConstants[2] === b &&
  9834. this._blendConstants[3] === a) {
  9835. return;
  9836. }
  9837. this._blendConstants[0] = r;
  9838. this._blendConstants[1] = g;
  9839. this._blendConstants[2] = b;
  9840. this._blendConstants[3] = a;
  9841. this._isBlendConstantsDirty = true;
  9842. };
  9843. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9844. if (this._blendFunctionParameters[0] === value0 &&
  9845. this._blendFunctionParameters[1] === value1 &&
  9846. this._blendFunctionParameters[2] === value2 &&
  9847. this._blendFunctionParameters[3] === value3) {
  9848. return;
  9849. }
  9850. this._blendFunctionParameters[0] = value0;
  9851. this._blendFunctionParameters[1] = value1;
  9852. this._blendFunctionParameters[2] = value2;
  9853. this._blendFunctionParameters[3] = value3;
  9854. this._isBlendFunctionParametersDirty = true;
  9855. };
  9856. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9857. if (this._blendEquationParameters[0] === rgb &&
  9858. this._blendEquationParameters[1] === alpha) {
  9859. return;
  9860. }
  9861. this._blendEquationParameters[0] = rgb;
  9862. this._blendEquationParameters[1] = alpha;
  9863. this._isBlendEquationParametersDirty = true;
  9864. };
  9865. _AlphaState.prototype.reset = function () {
  9866. this._alphaBlend = false;
  9867. this._blendFunctionParameters[0] = null;
  9868. this._blendFunctionParameters[1] = null;
  9869. this._blendFunctionParameters[2] = null;
  9870. this._blendFunctionParameters[3] = null;
  9871. this._blendEquationParameters[0] = null;
  9872. this._blendEquationParameters[1] = null;
  9873. this._blendConstants[0] = null;
  9874. this._blendConstants[1] = null;
  9875. this._blendConstants[2] = null;
  9876. this._blendConstants[3] = null;
  9877. this._isAlphaBlendDirty = true;
  9878. this._isBlendFunctionParametersDirty = false;
  9879. this._isBlendEquationParametersDirty = false;
  9880. this._isBlendConstantsDirty = false;
  9881. };
  9882. _AlphaState.prototype.apply = function (gl) {
  9883. if (!this.isDirty) {
  9884. return;
  9885. }
  9886. // Alpha blend
  9887. if (this._isAlphaBlendDirty) {
  9888. if (this._alphaBlend) {
  9889. gl.enable(gl.BLEND);
  9890. }
  9891. else {
  9892. gl.disable(gl.BLEND);
  9893. }
  9894. this._isAlphaBlendDirty = false;
  9895. }
  9896. // Alpha function
  9897. if (this._isBlendFunctionParametersDirty) {
  9898. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9899. this._isBlendFunctionParametersDirty = false;
  9900. }
  9901. // Alpha equation
  9902. if (this._isBlendEquationParametersDirty) {
  9903. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9904. this._isBlendEquationParametersDirty = false;
  9905. }
  9906. // Constants
  9907. if (this._isBlendConstantsDirty) {
  9908. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9909. this._isBlendConstantsDirty = false;
  9910. }
  9911. };
  9912. return _AlphaState;
  9913. }());
  9914. BABYLON._AlphaState = _AlphaState;
  9915. })(BABYLON || (BABYLON = {}));
  9916. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9917. var BABYLON;
  9918. (function (BABYLON) {
  9919. var _DepthCullingState = /** @class */ (function () {
  9920. /**
  9921. * Initializes the state.
  9922. */
  9923. function _DepthCullingState() {
  9924. this._isDepthTestDirty = false;
  9925. this._isDepthMaskDirty = false;
  9926. this._isDepthFuncDirty = false;
  9927. this._isCullFaceDirty = false;
  9928. this._isCullDirty = false;
  9929. this._isZOffsetDirty = false;
  9930. this._isFrontFaceDirty = false;
  9931. this.reset();
  9932. }
  9933. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9934. get: function () {
  9935. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9936. },
  9937. enumerable: true,
  9938. configurable: true
  9939. });
  9940. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9941. get: function () {
  9942. return this._zOffset;
  9943. },
  9944. set: function (value) {
  9945. if (this._zOffset === value) {
  9946. return;
  9947. }
  9948. this._zOffset = value;
  9949. this._isZOffsetDirty = true;
  9950. },
  9951. enumerable: true,
  9952. configurable: true
  9953. });
  9954. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9955. get: function () {
  9956. return this._cullFace;
  9957. },
  9958. set: function (value) {
  9959. if (this._cullFace === value) {
  9960. return;
  9961. }
  9962. this._cullFace = value;
  9963. this._isCullFaceDirty = true;
  9964. },
  9965. enumerable: true,
  9966. configurable: true
  9967. });
  9968. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9969. get: function () {
  9970. return this._cull;
  9971. },
  9972. set: function (value) {
  9973. if (this._cull === value) {
  9974. return;
  9975. }
  9976. this._cull = value;
  9977. this._isCullDirty = true;
  9978. },
  9979. enumerable: true,
  9980. configurable: true
  9981. });
  9982. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9983. get: function () {
  9984. return this._depthFunc;
  9985. },
  9986. set: function (value) {
  9987. if (this._depthFunc === value) {
  9988. return;
  9989. }
  9990. this._depthFunc = value;
  9991. this._isDepthFuncDirty = true;
  9992. },
  9993. enumerable: true,
  9994. configurable: true
  9995. });
  9996. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9997. get: function () {
  9998. return this._depthMask;
  9999. },
  10000. set: function (value) {
  10001. if (this._depthMask === value) {
  10002. return;
  10003. }
  10004. this._depthMask = value;
  10005. this._isDepthMaskDirty = true;
  10006. },
  10007. enumerable: true,
  10008. configurable: true
  10009. });
  10010. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10011. get: function () {
  10012. return this._depthTest;
  10013. },
  10014. set: function (value) {
  10015. if (this._depthTest === value) {
  10016. return;
  10017. }
  10018. this._depthTest = value;
  10019. this._isDepthTestDirty = true;
  10020. },
  10021. enumerable: true,
  10022. configurable: true
  10023. });
  10024. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10025. get: function () {
  10026. return this._frontFace;
  10027. },
  10028. set: function (value) {
  10029. if (this._frontFace === value) {
  10030. return;
  10031. }
  10032. this._frontFace = value;
  10033. this._isFrontFaceDirty = true;
  10034. },
  10035. enumerable: true,
  10036. configurable: true
  10037. });
  10038. _DepthCullingState.prototype.reset = function () {
  10039. this._depthMask = true;
  10040. this._depthTest = true;
  10041. this._depthFunc = null;
  10042. this._cullFace = null;
  10043. this._cull = null;
  10044. this._zOffset = 0;
  10045. this._frontFace = null;
  10046. this._isDepthTestDirty = true;
  10047. this._isDepthMaskDirty = true;
  10048. this._isDepthFuncDirty = false;
  10049. this._isCullFaceDirty = false;
  10050. this._isCullDirty = false;
  10051. this._isZOffsetDirty = false;
  10052. this._isFrontFaceDirty = false;
  10053. };
  10054. _DepthCullingState.prototype.apply = function (gl) {
  10055. if (!this.isDirty) {
  10056. return;
  10057. }
  10058. // Cull
  10059. if (this._isCullDirty) {
  10060. if (this.cull) {
  10061. gl.enable(gl.CULL_FACE);
  10062. }
  10063. else {
  10064. gl.disable(gl.CULL_FACE);
  10065. }
  10066. this._isCullDirty = false;
  10067. }
  10068. // Cull face
  10069. if (this._isCullFaceDirty) {
  10070. gl.cullFace(this.cullFace);
  10071. this._isCullFaceDirty = false;
  10072. }
  10073. // Depth mask
  10074. if (this._isDepthMaskDirty) {
  10075. gl.depthMask(this.depthMask);
  10076. this._isDepthMaskDirty = false;
  10077. }
  10078. // Depth test
  10079. if (this._isDepthTestDirty) {
  10080. if (this.depthTest) {
  10081. gl.enable(gl.DEPTH_TEST);
  10082. }
  10083. else {
  10084. gl.disable(gl.DEPTH_TEST);
  10085. }
  10086. this._isDepthTestDirty = false;
  10087. }
  10088. // Depth func
  10089. if (this._isDepthFuncDirty) {
  10090. gl.depthFunc(this.depthFunc);
  10091. this._isDepthFuncDirty = false;
  10092. }
  10093. // zOffset
  10094. if (this._isZOffsetDirty) {
  10095. if (this.zOffset) {
  10096. gl.enable(gl.POLYGON_OFFSET_FILL);
  10097. gl.polygonOffset(this.zOffset, 0);
  10098. }
  10099. else {
  10100. gl.disable(gl.POLYGON_OFFSET_FILL);
  10101. }
  10102. this._isZOffsetDirty = false;
  10103. }
  10104. // Front face
  10105. if (this._isFrontFaceDirty) {
  10106. gl.frontFace(this.frontFace);
  10107. this._isFrontFaceDirty = false;
  10108. }
  10109. };
  10110. return _DepthCullingState;
  10111. }());
  10112. BABYLON._DepthCullingState = _DepthCullingState;
  10113. })(BABYLON || (BABYLON = {}));
  10114. //# sourceMappingURL=babylon.depthCullingState.js.map
  10115. var BABYLON;
  10116. (function (BABYLON) {
  10117. var _StencilState = /** @class */ (function () {
  10118. function _StencilState() {
  10119. this._isStencilTestDirty = false;
  10120. this._isStencilMaskDirty = false;
  10121. this._isStencilFuncDirty = false;
  10122. this._isStencilOpDirty = false;
  10123. this.reset();
  10124. }
  10125. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10126. get: function () {
  10127. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10128. },
  10129. enumerable: true,
  10130. configurable: true
  10131. });
  10132. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10133. get: function () {
  10134. return this._stencilFunc;
  10135. },
  10136. set: function (value) {
  10137. if (this._stencilFunc === value) {
  10138. return;
  10139. }
  10140. this._stencilFunc = value;
  10141. this._isStencilFuncDirty = true;
  10142. },
  10143. enumerable: true,
  10144. configurable: true
  10145. });
  10146. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10147. get: function () {
  10148. return this._stencilFuncRef;
  10149. },
  10150. set: function (value) {
  10151. if (this._stencilFuncRef === value) {
  10152. return;
  10153. }
  10154. this._stencilFuncRef = value;
  10155. this._isStencilFuncDirty = true;
  10156. },
  10157. enumerable: true,
  10158. configurable: true
  10159. });
  10160. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10161. get: function () {
  10162. return this._stencilFuncMask;
  10163. },
  10164. set: function (value) {
  10165. if (this._stencilFuncMask === value) {
  10166. return;
  10167. }
  10168. this._stencilFuncMask = value;
  10169. this._isStencilFuncDirty = true;
  10170. },
  10171. enumerable: true,
  10172. configurable: true
  10173. });
  10174. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10175. get: function () {
  10176. return this._stencilOpStencilFail;
  10177. },
  10178. set: function (value) {
  10179. if (this._stencilOpStencilFail === value) {
  10180. return;
  10181. }
  10182. this._stencilOpStencilFail = value;
  10183. this._isStencilOpDirty = true;
  10184. },
  10185. enumerable: true,
  10186. configurable: true
  10187. });
  10188. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10189. get: function () {
  10190. return this._stencilOpDepthFail;
  10191. },
  10192. set: function (value) {
  10193. if (this._stencilOpDepthFail === value) {
  10194. return;
  10195. }
  10196. this._stencilOpDepthFail = value;
  10197. this._isStencilOpDirty = true;
  10198. },
  10199. enumerable: true,
  10200. configurable: true
  10201. });
  10202. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10203. get: function () {
  10204. return this._stencilOpStencilDepthPass;
  10205. },
  10206. set: function (value) {
  10207. if (this._stencilOpStencilDepthPass === value) {
  10208. return;
  10209. }
  10210. this._stencilOpStencilDepthPass = value;
  10211. this._isStencilOpDirty = true;
  10212. },
  10213. enumerable: true,
  10214. configurable: true
  10215. });
  10216. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10217. get: function () {
  10218. return this._stencilMask;
  10219. },
  10220. set: function (value) {
  10221. if (this._stencilMask === value) {
  10222. return;
  10223. }
  10224. this._stencilMask = value;
  10225. this._isStencilMaskDirty = true;
  10226. },
  10227. enumerable: true,
  10228. configurable: true
  10229. });
  10230. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10231. get: function () {
  10232. return this._stencilTest;
  10233. },
  10234. set: function (value) {
  10235. if (this._stencilTest === value) {
  10236. return;
  10237. }
  10238. this._stencilTest = value;
  10239. this._isStencilTestDirty = true;
  10240. },
  10241. enumerable: true,
  10242. configurable: true
  10243. });
  10244. _StencilState.prototype.reset = function () {
  10245. this._stencilTest = false;
  10246. this._stencilMask = 0xFF;
  10247. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10248. this._stencilFuncRef = 1;
  10249. this._stencilFuncMask = 0xFF;
  10250. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10251. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10252. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10253. this._isStencilTestDirty = true;
  10254. this._isStencilMaskDirty = true;
  10255. this._isStencilFuncDirty = true;
  10256. this._isStencilOpDirty = true;
  10257. };
  10258. _StencilState.prototype.apply = function (gl) {
  10259. if (!this.isDirty) {
  10260. return;
  10261. }
  10262. // Stencil test
  10263. if (this._isStencilTestDirty) {
  10264. if (this.stencilTest) {
  10265. gl.enable(gl.STENCIL_TEST);
  10266. }
  10267. else {
  10268. gl.disable(gl.STENCIL_TEST);
  10269. }
  10270. this._isStencilTestDirty = false;
  10271. }
  10272. // Stencil mask
  10273. if (this._isStencilMaskDirty) {
  10274. gl.stencilMask(this.stencilMask);
  10275. this._isStencilMaskDirty = false;
  10276. }
  10277. // Stencil func
  10278. if (this._isStencilFuncDirty) {
  10279. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10280. this._isStencilFuncDirty = false;
  10281. }
  10282. // Stencil op
  10283. if (this._isStencilOpDirty) {
  10284. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10285. this._isStencilOpDirty = false;
  10286. }
  10287. };
  10288. return _StencilState;
  10289. }());
  10290. BABYLON._StencilState = _StencilState;
  10291. })(BABYLON || (BABYLON = {}));
  10292. //# sourceMappingURL=babylon.stencilState.js.map
  10293. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10294. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10295. s = arguments[i];
  10296. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10297. t[p] = s[p];
  10298. }
  10299. return t;
  10300. };
  10301. var BABYLON;
  10302. (function (BABYLON) {
  10303. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10304. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10305. };
  10306. var compileRawShader = function (gl, source, type) {
  10307. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10308. gl.shaderSource(shader, source);
  10309. gl.compileShader(shader);
  10310. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10311. var log = gl.getShaderInfoLog(shader);
  10312. if (log) {
  10313. throw new Error(log);
  10314. }
  10315. }
  10316. if (!shader) {
  10317. throw new Error("Something went wrong while compile the shader.");
  10318. }
  10319. return shader;
  10320. };
  10321. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10322. var magFilter = gl.NEAREST;
  10323. var minFilter = gl.NEAREST;
  10324. switch (samplingMode) {
  10325. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10326. magFilter = gl.LINEAR;
  10327. if (generateMipMaps) {
  10328. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10329. }
  10330. else {
  10331. minFilter = gl.LINEAR;
  10332. }
  10333. break;
  10334. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10335. magFilter = gl.LINEAR;
  10336. if (generateMipMaps) {
  10337. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10338. }
  10339. else {
  10340. minFilter = gl.LINEAR;
  10341. }
  10342. break;
  10343. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10344. magFilter = gl.NEAREST;
  10345. if (generateMipMaps) {
  10346. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10347. }
  10348. else {
  10349. minFilter = gl.NEAREST;
  10350. }
  10351. break;
  10352. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10353. magFilter = gl.NEAREST;
  10354. if (generateMipMaps) {
  10355. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10356. }
  10357. else {
  10358. minFilter = gl.NEAREST;
  10359. }
  10360. break;
  10361. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10362. magFilter = gl.NEAREST;
  10363. if (generateMipMaps) {
  10364. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10365. }
  10366. else {
  10367. minFilter = gl.LINEAR;
  10368. }
  10369. break;
  10370. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10371. magFilter = gl.NEAREST;
  10372. if (generateMipMaps) {
  10373. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10374. }
  10375. else {
  10376. minFilter = gl.LINEAR;
  10377. }
  10378. break;
  10379. case BABYLON.Texture.NEAREST_LINEAR:
  10380. magFilter = gl.NEAREST;
  10381. minFilter = gl.LINEAR;
  10382. break;
  10383. case BABYLON.Texture.NEAREST_NEAREST:
  10384. magFilter = gl.NEAREST;
  10385. minFilter = gl.NEAREST;
  10386. break;
  10387. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10388. magFilter = gl.LINEAR;
  10389. if (generateMipMaps) {
  10390. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10391. }
  10392. else {
  10393. minFilter = gl.NEAREST;
  10394. }
  10395. break;
  10396. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10397. magFilter = gl.LINEAR;
  10398. if (generateMipMaps) {
  10399. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10400. }
  10401. else {
  10402. minFilter = gl.NEAREST;
  10403. }
  10404. break;
  10405. case BABYLON.Texture.LINEAR_LINEAR:
  10406. magFilter = gl.LINEAR;
  10407. minFilter = gl.LINEAR;
  10408. break;
  10409. case BABYLON.Texture.LINEAR_NEAREST:
  10410. magFilter = gl.LINEAR;
  10411. minFilter = gl.NEAREST;
  10412. break;
  10413. }
  10414. return {
  10415. min: minFilter,
  10416. mag: magFilter
  10417. };
  10418. };
  10419. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10420. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10421. var img;
  10422. var onload = function () {
  10423. loadedImages[index] = img;
  10424. loadedImages._internalCount++;
  10425. if (scene) {
  10426. scene._removePendingData(img);
  10427. }
  10428. if (loadedImages._internalCount === 6) {
  10429. onfinish(loadedImages);
  10430. }
  10431. };
  10432. var onerror = function (message, exception) {
  10433. if (scene) {
  10434. scene._removePendingData(img);
  10435. }
  10436. if (onErrorCallBack) {
  10437. onErrorCallBack(message, exception);
  10438. }
  10439. };
  10440. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10441. if (scene) {
  10442. scene._addPendingData(img);
  10443. }
  10444. };
  10445. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10446. if (onError === void 0) { onError = null; }
  10447. var loadedImages = [];
  10448. loadedImages._internalCount = 0;
  10449. for (var index = 0; index < 6; index++) {
  10450. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10451. }
  10452. };
  10453. var BufferPointer = /** @class */ (function () {
  10454. function BufferPointer() {
  10455. }
  10456. return BufferPointer;
  10457. }());
  10458. var InstancingAttributeInfo = /** @class */ (function () {
  10459. function InstancingAttributeInfo() {
  10460. }
  10461. return InstancingAttributeInfo;
  10462. }());
  10463. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10464. /**
  10465. * Define options used to create a render target texture
  10466. */
  10467. var RenderTargetCreationOptions = /** @class */ (function () {
  10468. function RenderTargetCreationOptions() {
  10469. }
  10470. return RenderTargetCreationOptions;
  10471. }());
  10472. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10473. /**
  10474. * Define options used to create a depth texture
  10475. */
  10476. var DepthTextureCreationOptions = /** @class */ (function () {
  10477. function DepthTextureCreationOptions() {
  10478. }
  10479. return DepthTextureCreationOptions;
  10480. }());
  10481. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10482. /**
  10483. * Regroup several parameters relative to the browser in use
  10484. */
  10485. var EngineCapabilities = /** @class */ (function () {
  10486. function EngineCapabilities() {
  10487. }
  10488. return EngineCapabilities;
  10489. }());
  10490. BABYLON.EngineCapabilities = EngineCapabilities;
  10491. /**
  10492. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10493. */
  10494. var Engine = /** @class */ (function () {
  10495. /**
  10496. * @constructor
  10497. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10498. * @param antialias defines enable antialiasing (default: false)
  10499. * @param options defines further options to be sent to the getContext() function
  10500. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10501. */
  10502. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10503. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10504. var _this = this;
  10505. // Public members
  10506. this.forcePOTTextures = false;
  10507. this.isFullscreen = false;
  10508. this.isPointerLock = false;
  10509. this.cullBackFaces = true;
  10510. this.renderEvenInBackground = true;
  10511. this.preventCacheWipeBetweenFrames = false;
  10512. // To enable/disable IDB support and avoid XHR on .manifest
  10513. this.enableOfflineSupport = false;
  10514. this.scenes = new Array();
  10515. this.postProcesses = new Array();
  10516. // Observables
  10517. /**
  10518. * Observable event triggered each time the rendering canvas is resized
  10519. */
  10520. this.onResizeObservable = new BABYLON.Observable();
  10521. /**
  10522. * Observable event triggered each time the canvas loses focus
  10523. */
  10524. this.onCanvasBlurObservable = new BABYLON.Observable();
  10525. /**
  10526. * Observable event triggered each time the canvas gains focus
  10527. */
  10528. this.onCanvasFocusObservable = new BABYLON.Observable();
  10529. /**
  10530. * Observable event triggered each time the canvas receives pointerout event
  10531. */
  10532. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10533. /**
  10534. * Observable event triggered before each texture is initialized
  10535. */
  10536. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10537. //WebVR
  10538. this._vrDisplay = undefined;
  10539. this._vrSupported = false;
  10540. this._vrExclusivePointerMode = false;
  10541. // Uniform buffers list
  10542. this.disableUniformBuffers = false;
  10543. this._uniformBuffers = new Array();
  10544. // Observables
  10545. /**
  10546. * Observable raised when the engine begins a new frame
  10547. */
  10548. this.onBeginFrameObservable = new BABYLON.Observable();
  10549. /**
  10550. * Observable raised when the engine ends the current frame
  10551. */
  10552. this.onEndFrameObservable = new BABYLON.Observable();
  10553. /**
  10554. * Observable raised when the engine is about to compile a shader
  10555. */
  10556. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10557. /**
  10558. * Observable raised when the engine has jsut compiled a shader
  10559. */
  10560. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10561. this._windowIsBackground = false;
  10562. this._webGLVersion = 1.0;
  10563. this._badOS = false;
  10564. this._badDesktopOS = false;
  10565. /**
  10566. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10567. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10568. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10569. */
  10570. this.disableTextureBindingOptimization = false;
  10571. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10572. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10573. this.onVRRequestPresentStart = new BABYLON.Observable();
  10574. this._colorWrite = true;
  10575. this._drawCalls = new BABYLON.PerfCounter();
  10576. this._textureCollisions = new BABYLON.PerfCounter();
  10577. this._renderingQueueLaunched = false;
  10578. this._activeRenderLoops = new Array();
  10579. // Deterministic lockstepMaxSteps
  10580. this._deterministicLockstep = false;
  10581. this._lockstepMaxSteps = 4;
  10582. // Lost context
  10583. this.onContextLostObservable = new BABYLON.Observable();
  10584. this.onContextRestoredObservable = new BABYLON.Observable();
  10585. this._contextWasLost = false;
  10586. this._doNotHandleContextLost = false;
  10587. // FPS
  10588. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10589. this._fps = 60;
  10590. this._deltaTime = 0;
  10591. /**
  10592. * Turn this value on if you want to pause FPS computation when in background
  10593. */
  10594. this.disablePerformanceMonitorInBackground = false;
  10595. // States
  10596. this._depthCullingState = new BABYLON._DepthCullingState();
  10597. this._stencilState = new BABYLON._StencilState();
  10598. this._alphaState = new BABYLON._AlphaState();
  10599. this._alphaMode = Engine.ALPHA_DISABLE;
  10600. // Cache
  10601. this._internalTexturesCache = new Array();
  10602. this._activeChannel = 0;
  10603. this._currentTextureChannel = -1;
  10604. this._boundTexturesCache = {};
  10605. this._compiledEffects = {};
  10606. this._vertexAttribArraysEnabled = [];
  10607. this._uintIndicesCurrentlySet = false;
  10608. this._currentBoundBuffer = new Array();
  10609. this._currentBufferPointers = new Array();
  10610. this._currentInstanceLocations = new Array();
  10611. this._currentInstanceBuffers = new Array();
  10612. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10613. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10614. this._vaoRecordInProgress = false;
  10615. this._mustWipeVertexAttributes = false;
  10616. this._nextFreeTextureSlots = new Array();
  10617. this._maxSimultaneousTextures = 0;
  10618. this._activeRequests = new Array();
  10619. // Hardware supported Compressed Textures
  10620. this._texturesSupported = new Array();
  10621. this._onVRFullScreenTriggered = function () {
  10622. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10623. //get the old size before we change
  10624. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10625. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10626. //get the width and height, change the render size
  10627. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10628. _this.setHardwareScalingLevel(1);
  10629. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10630. }
  10631. else {
  10632. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10633. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10634. }
  10635. };
  10636. this._boundUniforms = {};
  10637. // Register promises
  10638. BABYLON.PromisePolyfill.Apply();
  10639. var canvas = null;
  10640. Engine.Instances.push(this);
  10641. if (!canvasOrContext) {
  10642. return;
  10643. }
  10644. options = options || {};
  10645. if (canvasOrContext.getContext) {
  10646. canvas = canvasOrContext;
  10647. this._renderingCanvas = canvas;
  10648. if (antialias != null) {
  10649. options.antialias = antialias;
  10650. }
  10651. if (options.deterministicLockstep === undefined) {
  10652. options.deterministicLockstep = false;
  10653. }
  10654. if (options.lockstepMaxSteps === undefined) {
  10655. options.lockstepMaxSteps = 4;
  10656. }
  10657. if (options.preserveDrawingBuffer === undefined) {
  10658. options.preserveDrawingBuffer = false;
  10659. }
  10660. if (options.audioEngine === undefined) {
  10661. options.audioEngine = true;
  10662. }
  10663. if (options.stencil === undefined) {
  10664. options.stencil = true;
  10665. }
  10666. this._deterministicLockstep = options.deterministicLockstep;
  10667. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10668. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10669. // Exceptions
  10670. if (navigator && navigator.userAgent) {
  10671. var ua = navigator.userAgent;
  10672. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10673. var exception = _a[_i];
  10674. var key = exception.key;
  10675. var targets = exception.targets;
  10676. if (ua.indexOf(key) > -1) {
  10677. if (exception.capture && exception.captureConstraint) {
  10678. var capture = exception.capture;
  10679. var constraint = exception.captureConstraint;
  10680. var regex = new RegExp(capture);
  10681. var matches = regex.exec(ua);
  10682. if (matches && matches.length > 0) {
  10683. var capturedValue = parseInt(matches[matches.length - 1]);
  10684. if (capturedValue >= constraint) {
  10685. continue;
  10686. }
  10687. }
  10688. }
  10689. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10690. var target = targets_1[_b];
  10691. switch (target) {
  10692. case "uniformBuffer":
  10693. this.disableUniformBuffers = true;
  10694. break;
  10695. case "textureBindingOptimization":
  10696. this.disableTextureBindingOptimization = true;
  10697. break;
  10698. }
  10699. }
  10700. }
  10701. }
  10702. }
  10703. // GL
  10704. if (!options.disableWebGL2Support) {
  10705. try {
  10706. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10707. if (this._gl) {
  10708. this._webGLVersion = 2.0;
  10709. }
  10710. }
  10711. catch (e) {
  10712. // Do nothing
  10713. }
  10714. }
  10715. if (!this._gl) {
  10716. if (!canvas) {
  10717. throw new Error("The provided canvas is null or undefined.");
  10718. }
  10719. try {
  10720. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10721. }
  10722. catch (e) {
  10723. throw new Error("WebGL not supported");
  10724. }
  10725. }
  10726. if (!this._gl) {
  10727. throw new Error("WebGL not supported");
  10728. }
  10729. this._onCanvasFocus = function () {
  10730. _this.onCanvasFocusObservable.notifyObservers(_this);
  10731. };
  10732. this._onCanvasBlur = function () {
  10733. _this.onCanvasBlurObservable.notifyObservers(_this);
  10734. };
  10735. canvas.addEventListener("focus", this._onCanvasFocus);
  10736. canvas.addEventListener("blur", this._onCanvasBlur);
  10737. this._onBlur = function () {
  10738. if (_this.disablePerformanceMonitorInBackground) {
  10739. _this._performanceMonitor.disable();
  10740. }
  10741. _this._windowIsBackground = true;
  10742. };
  10743. this._onFocus = function () {
  10744. if (_this.disablePerformanceMonitorInBackground) {
  10745. _this._performanceMonitor.enable();
  10746. }
  10747. _this._windowIsBackground = false;
  10748. };
  10749. this._onCanvasPointerOut = function (ev) {
  10750. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10751. };
  10752. window.addEventListener("blur", this._onBlur);
  10753. window.addEventListener("focus", this._onFocus);
  10754. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10755. // Context lost
  10756. if (!this._doNotHandleContextLost) {
  10757. this._onContextLost = function (evt) {
  10758. evt.preventDefault();
  10759. _this._contextWasLost = true;
  10760. BABYLON.Tools.Warn("WebGL context lost.");
  10761. _this.onContextLostObservable.notifyObservers(_this);
  10762. };
  10763. this._onContextRestored = function (evt) {
  10764. // Adding a timeout to avoid race condition at browser level
  10765. setTimeout(function () {
  10766. // Rebuild gl context
  10767. _this._initGLContext();
  10768. // Rebuild effects
  10769. _this._rebuildEffects();
  10770. // Rebuild textures
  10771. _this._rebuildInternalTextures();
  10772. // Rebuild buffers
  10773. _this._rebuildBuffers();
  10774. // Cache
  10775. _this.wipeCaches(true);
  10776. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10777. _this.onContextRestoredObservable.notifyObservers(_this);
  10778. _this._contextWasLost = false;
  10779. }, 0);
  10780. };
  10781. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10782. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10783. }
  10784. }
  10785. else {
  10786. this._gl = canvasOrContext;
  10787. this._renderingCanvas = this._gl.canvas;
  10788. if (this._gl.renderbufferStorageMultisample) {
  10789. this._webGLVersion = 2.0;
  10790. }
  10791. options.stencil = this._gl.getContextAttributes().stencil;
  10792. }
  10793. // Viewport
  10794. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10795. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10796. this.resize();
  10797. this._isStencilEnable = options.stencil ? true : false;
  10798. this._initGLContext();
  10799. if (canvas) {
  10800. // Fullscreen
  10801. this._onFullscreenChange = function () {
  10802. if (document.fullscreen !== undefined) {
  10803. _this.isFullscreen = document.fullscreen;
  10804. }
  10805. else if (document.mozFullScreen !== undefined) {
  10806. _this.isFullscreen = document.mozFullScreen;
  10807. }
  10808. else if (document.webkitIsFullScreen !== undefined) {
  10809. _this.isFullscreen = document.webkitIsFullScreen;
  10810. }
  10811. else if (document.msIsFullScreen !== undefined) {
  10812. _this.isFullscreen = document.msIsFullScreen;
  10813. }
  10814. // Pointer lock
  10815. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10816. canvas.requestPointerLock = canvas.requestPointerLock ||
  10817. canvas.msRequestPointerLock ||
  10818. canvas.mozRequestPointerLock ||
  10819. canvas.webkitRequestPointerLock;
  10820. if (canvas.requestPointerLock) {
  10821. canvas.requestPointerLock();
  10822. }
  10823. }
  10824. };
  10825. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10826. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10827. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10828. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10829. // Pointer lock
  10830. this._onPointerLockChange = function () {
  10831. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10832. document.webkitPointerLockElement === canvas ||
  10833. document.msPointerLockElement === canvas ||
  10834. document.pointerLockElement === canvas);
  10835. };
  10836. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10837. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10838. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10839. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10840. this._onVRDisplayPointerRestricted = function () {
  10841. if (canvas) {
  10842. canvas.requestPointerLock();
  10843. }
  10844. };
  10845. this._onVRDisplayPointerUnrestricted = function () {
  10846. document.exitPointerLock();
  10847. };
  10848. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10849. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10850. }
  10851. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10852. Engine.audioEngine = new BABYLON.AudioEngine();
  10853. }
  10854. // Prepare buffer pointers
  10855. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10856. this._currentBufferPointers[i] = new BufferPointer();
  10857. }
  10858. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10859. // Load WebVR Devices
  10860. if (options.autoEnableWebVR) {
  10861. this.initWebVR();
  10862. }
  10863. // Detect if we are running on a faulty buggy OS.
  10864. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10865. // Detect if we are running on a faulty buggy desktop OS.
  10866. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10867. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  10868. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10869. }
  10870. Object.defineProperty(Engine, "LastCreatedEngine", {
  10871. get: function () {
  10872. if (Engine.Instances.length === 0) {
  10873. return null;
  10874. }
  10875. return Engine.Instances[Engine.Instances.length - 1];
  10876. },
  10877. enumerable: true,
  10878. configurable: true
  10879. });
  10880. Object.defineProperty(Engine, "LastCreatedScene", {
  10881. get: function () {
  10882. var lastCreatedEngine = Engine.LastCreatedEngine;
  10883. if (!lastCreatedEngine) {
  10884. return null;
  10885. }
  10886. if (lastCreatedEngine.scenes.length === 0) {
  10887. return null;
  10888. }
  10889. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10890. },
  10891. enumerable: true,
  10892. configurable: true
  10893. });
  10894. /**
  10895. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10896. */
  10897. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10898. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10899. var engine = Engine.Instances[engineIndex];
  10900. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10901. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10902. }
  10903. }
  10904. };
  10905. Object.defineProperty(Engine, "NEVER", {
  10906. get: function () {
  10907. return Engine._NEVER;
  10908. },
  10909. enumerable: true,
  10910. configurable: true
  10911. });
  10912. Object.defineProperty(Engine, "ALWAYS", {
  10913. get: function () {
  10914. return Engine._ALWAYS;
  10915. },
  10916. enumerable: true,
  10917. configurable: true
  10918. });
  10919. Object.defineProperty(Engine, "LESS", {
  10920. get: function () {
  10921. return Engine._LESS;
  10922. },
  10923. enumerable: true,
  10924. configurable: true
  10925. });
  10926. Object.defineProperty(Engine, "EQUAL", {
  10927. get: function () {
  10928. return Engine._EQUAL;
  10929. },
  10930. enumerable: true,
  10931. configurable: true
  10932. });
  10933. Object.defineProperty(Engine, "LEQUAL", {
  10934. get: function () {
  10935. return Engine._LEQUAL;
  10936. },
  10937. enumerable: true,
  10938. configurable: true
  10939. });
  10940. Object.defineProperty(Engine, "GREATER", {
  10941. get: function () {
  10942. return Engine._GREATER;
  10943. },
  10944. enumerable: true,
  10945. configurable: true
  10946. });
  10947. Object.defineProperty(Engine, "GEQUAL", {
  10948. get: function () {
  10949. return Engine._GEQUAL;
  10950. },
  10951. enumerable: true,
  10952. configurable: true
  10953. });
  10954. Object.defineProperty(Engine, "NOTEQUAL", {
  10955. get: function () {
  10956. return Engine._NOTEQUAL;
  10957. },
  10958. enumerable: true,
  10959. configurable: true
  10960. });
  10961. Object.defineProperty(Engine, "KEEP", {
  10962. get: function () {
  10963. return Engine._KEEP;
  10964. },
  10965. enumerable: true,
  10966. configurable: true
  10967. });
  10968. Object.defineProperty(Engine, "REPLACE", {
  10969. get: function () {
  10970. return Engine._REPLACE;
  10971. },
  10972. enumerable: true,
  10973. configurable: true
  10974. });
  10975. Object.defineProperty(Engine, "INCR", {
  10976. get: function () {
  10977. return Engine._INCR;
  10978. },
  10979. enumerable: true,
  10980. configurable: true
  10981. });
  10982. Object.defineProperty(Engine, "DECR", {
  10983. get: function () {
  10984. return Engine._DECR;
  10985. },
  10986. enumerable: true,
  10987. configurable: true
  10988. });
  10989. Object.defineProperty(Engine, "INVERT", {
  10990. get: function () {
  10991. return Engine._INVERT;
  10992. },
  10993. enumerable: true,
  10994. configurable: true
  10995. });
  10996. Object.defineProperty(Engine, "INCR_WRAP", {
  10997. get: function () {
  10998. return Engine._INCR_WRAP;
  10999. },
  11000. enumerable: true,
  11001. configurable: true
  11002. });
  11003. Object.defineProperty(Engine, "DECR_WRAP", {
  11004. get: function () {
  11005. return Engine._DECR_WRAP;
  11006. },
  11007. enumerable: true,
  11008. configurable: true
  11009. });
  11010. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11011. get: function () {
  11012. return Engine._ALPHA_DISABLE;
  11013. },
  11014. enumerable: true,
  11015. configurable: true
  11016. });
  11017. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11018. get: function () {
  11019. return Engine._ALPHA_ONEONE;
  11020. },
  11021. enumerable: true,
  11022. configurable: true
  11023. });
  11024. Object.defineProperty(Engine, "ALPHA_ADD", {
  11025. get: function () {
  11026. return Engine._ALPHA_ADD;
  11027. },
  11028. enumerable: true,
  11029. configurable: true
  11030. });
  11031. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11032. get: function () {
  11033. return Engine._ALPHA_COMBINE;
  11034. },
  11035. enumerable: true,
  11036. configurable: true
  11037. });
  11038. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11039. get: function () {
  11040. return Engine._ALPHA_SUBTRACT;
  11041. },
  11042. enumerable: true,
  11043. configurable: true
  11044. });
  11045. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11046. get: function () {
  11047. return Engine._ALPHA_MULTIPLY;
  11048. },
  11049. enumerable: true,
  11050. configurable: true
  11051. });
  11052. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11053. get: function () {
  11054. return Engine._ALPHA_MAXIMIZED;
  11055. },
  11056. enumerable: true,
  11057. configurable: true
  11058. });
  11059. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11060. get: function () {
  11061. return Engine._ALPHA_PREMULTIPLIED;
  11062. },
  11063. enumerable: true,
  11064. configurable: true
  11065. });
  11066. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11067. get: function () {
  11068. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11069. },
  11070. enumerable: true,
  11071. configurable: true
  11072. });
  11073. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11074. get: function () {
  11075. return Engine._ALPHA_INTERPOLATE;
  11076. },
  11077. enumerable: true,
  11078. configurable: true
  11079. });
  11080. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11081. get: function () {
  11082. return Engine._ALPHA_SCREENMODE;
  11083. },
  11084. enumerable: true,
  11085. configurable: true
  11086. });
  11087. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11088. get: function () {
  11089. return Engine._DELAYLOADSTATE_NONE;
  11090. },
  11091. enumerable: true,
  11092. configurable: true
  11093. });
  11094. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11095. get: function () {
  11096. return Engine._DELAYLOADSTATE_LOADED;
  11097. },
  11098. enumerable: true,
  11099. configurable: true
  11100. });
  11101. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11102. get: function () {
  11103. return Engine._DELAYLOADSTATE_LOADING;
  11104. },
  11105. enumerable: true,
  11106. configurable: true
  11107. });
  11108. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11109. get: function () {
  11110. return Engine._DELAYLOADSTATE_NOTLOADED;
  11111. },
  11112. enumerable: true,
  11113. configurable: true
  11114. });
  11115. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11116. get: function () {
  11117. return Engine._TEXTUREFORMAT_ALPHA;
  11118. },
  11119. enumerable: true,
  11120. configurable: true
  11121. });
  11122. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11123. get: function () {
  11124. return Engine._TEXTUREFORMAT_LUMINANCE;
  11125. },
  11126. enumerable: true,
  11127. configurable: true
  11128. });
  11129. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11130. /**
  11131. * R32F
  11132. */
  11133. get: function () {
  11134. return Engine._TEXTUREFORMAT_R32F;
  11135. },
  11136. enumerable: true,
  11137. configurable: true
  11138. });
  11139. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11140. /**
  11141. * RG32F
  11142. */
  11143. get: function () {
  11144. return Engine._TEXTUREFORMAT_RG32F;
  11145. },
  11146. enumerable: true,
  11147. configurable: true
  11148. });
  11149. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11150. /**
  11151. * RGB32F
  11152. */
  11153. get: function () {
  11154. return Engine._TEXTUREFORMAT_RGB32F;
  11155. },
  11156. enumerable: true,
  11157. configurable: true
  11158. });
  11159. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11160. /**
  11161. * RGBA32F
  11162. */
  11163. get: function () {
  11164. return Engine._TEXTUREFORMAT_RGBA32F;
  11165. },
  11166. enumerable: true,
  11167. configurable: true
  11168. });
  11169. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11170. get: function () {
  11171. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11172. },
  11173. enumerable: true,
  11174. configurable: true
  11175. });
  11176. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11177. get: function () {
  11178. return Engine._TEXTUREFORMAT_RGB;
  11179. },
  11180. enumerable: true,
  11181. configurable: true
  11182. });
  11183. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11184. get: function () {
  11185. return Engine._TEXTUREFORMAT_RGBA;
  11186. },
  11187. enumerable: true,
  11188. configurable: true
  11189. });
  11190. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11191. get: function () {
  11192. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11193. },
  11194. enumerable: true,
  11195. configurable: true
  11196. });
  11197. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11198. get: function () {
  11199. return Engine._TEXTURETYPE_FLOAT;
  11200. },
  11201. enumerable: true,
  11202. configurable: true
  11203. });
  11204. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11205. get: function () {
  11206. return Engine._TEXTURETYPE_HALF_FLOAT;
  11207. },
  11208. enumerable: true,
  11209. configurable: true
  11210. });
  11211. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11212. get: function () {
  11213. return Engine._SCALEMODE_FLOOR;
  11214. },
  11215. enumerable: true,
  11216. configurable: true
  11217. });
  11218. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11219. get: function () {
  11220. return Engine._SCALEMODE_NEAREST;
  11221. },
  11222. enumerable: true,
  11223. configurable: true
  11224. });
  11225. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11226. get: function () {
  11227. return Engine._SCALEMODE_CEILING;
  11228. },
  11229. enumerable: true,
  11230. configurable: true
  11231. });
  11232. Object.defineProperty(Engine, "Version", {
  11233. get: function () {
  11234. return "3.2.0-alphaC";
  11235. },
  11236. enumerable: true,
  11237. configurable: true
  11238. });
  11239. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11240. get: function () {
  11241. return this._vrExclusivePointerMode;
  11242. },
  11243. enumerable: true,
  11244. configurable: true
  11245. });
  11246. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11247. get: function () {
  11248. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11249. },
  11250. enumerable: true,
  11251. configurable: true
  11252. });
  11253. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11254. get: function () {
  11255. return this._webGLVersion < 2 || this.forcePOTTextures;
  11256. },
  11257. enumerable: true,
  11258. configurable: true
  11259. });
  11260. Object.defineProperty(Engine.prototype, "badOS", {
  11261. get: function () {
  11262. return this._badOS;
  11263. },
  11264. enumerable: true,
  11265. configurable: true
  11266. });
  11267. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11268. get: function () {
  11269. return this._badDesktopOS;
  11270. },
  11271. enumerable: true,
  11272. configurable: true
  11273. });
  11274. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11275. get: function () {
  11276. return this._performanceMonitor;
  11277. },
  11278. enumerable: true,
  11279. configurable: true
  11280. });
  11281. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11282. get: function () {
  11283. return this._texturesSupported;
  11284. },
  11285. enumerable: true,
  11286. configurable: true
  11287. });
  11288. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11289. get: function () {
  11290. return this._textureFormatInUse;
  11291. },
  11292. enumerable: true,
  11293. configurable: true
  11294. });
  11295. Object.defineProperty(Engine.prototype, "currentViewport", {
  11296. get: function () {
  11297. return this._cachedViewport;
  11298. },
  11299. enumerable: true,
  11300. configurable: true
  11301. });
  11302. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11303. // Empty texture
  11304. get: function () {
  11305. if (!this._emptyTexture) {
  11306. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11307. }
  11308. return this._emptyTexture;
  11309. },
  11310. enumerable: true,
  11311. configurable: true
  11312. });
  11313. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11314. get: function () {
  11315. if (!this._emptyTexture3D) {
  11316. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11317. }
  11318. return this._emptyTexture3D;
  11319. },
  11320. enumerable: true,
  11321. configurable: true
  11322. });
  11323. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11324. get: function () {
  11325. if (!this._emptyCubeTexture) {
  11326. var faceData = new Uint8Array(4);
  11327. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11328. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11329. }
  11330. return this._emptyCubeTexture;
  11331. },
  11332. enumerable: true,
  11333. configurable: true
  11334. });
  11335. Engine.prototype._rebuildInternalTextures = function () {
  11336. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11337. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11338. var internalTexture = currentState_1[_i];
  11339. internalTexture._rebuild();
  11340. }
  11341. };
  11342. Engine.prototype._rebuildEffects = function () {
  11343. for (var key in this._compiledEffects) {
  11344. var effect = this._compiledEffects[key];
  11345. effect._prepareEffect();
  11346. }
  11347. BABYLON.Effect.ResetCache();
  11348. };
  11349. Engine.prototype._rebuildBuffers = function () {
  11350. // Index / Vertex
  11351. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11352. var scene = _a[_i];
  11353. scene.resetCachedMaterial();
  11354. scene._rebuildGeometries();
  11355. scene._rebuildTextures();
  11356. }
  11357. // Uniforms
  11358. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11359. var uniformBuffer = _c[_b];
  11360. uniformBuffer._rebuild();
  11361. }
  11362. };
  11363. Engine.prototype._initGLContext = function () {
  11364. // Caps
  11365. this._caps = new EngineCapabilities();
  11366. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11367. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11368. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11369. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11370. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11371. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11372. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11373. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11374. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11375. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11376. // Infos
  11377. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11378. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11379. if (rendererInfo != null) {
  11380. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11381. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11382. }
  11383. if (!this._glVendor) {
  11384. this._glVendor = "Unknown vendor";
  11385. }
  11386. if (!this._glRenderer) {
  11387. this._glRenderer = "Unknown renderer";
  11388. }
  11389. // Constants
  11390. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11391. if (this._gl.RGBA16F !== 0x881A) {
  11392. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11393. }
  11394. if (this._gl.RGBA32F !== 0x8814) {
  11395. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11396. }
  11397. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11398. this._gl.DEPTH24_STENCIL8 = 35056;
  11399. }
  11400. // Extensions
  11401. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11402. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11403. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11404. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11405. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11406. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11407. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11408. 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');
  11409. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11410. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11411. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11412. this._caps.highPrecisionShaderSupported = true;
  11413. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11414. if (this._caps.timerQuery) {
  11415. if (this._webGLVersion === 1) {
  11416. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11417. }
  11418. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11419. }
  11420. // Checks if some of the format renders first to allow the use of webgl inspector.
  11421. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11422. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  11423. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  11424. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  11425. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  11426. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  11427. if (this._webGLVersion > 1) {
  11428. this._gl.HALF_FLOAT_OES = 0x140B;
  11429. }
  11430. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11431. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  11432. // Draw buffers
  11433. if (this._webGLVersion > 1) {
  11434. this._caps.drawBuffersExtension = true;
  11435. }
  11436. else {
  11437. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11438. if (drawBuffersExtension !== null) {
  11439. this._caps.drawBuffersExtension = true;
  11440. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11441. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11442. for (var i = 0; i < 16; i++) {
  11443. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11444. }
  11445. }
  11446. else {
  11447. this._caps.drawBuffersExtension = false;
  11448. }
  11449. }
  11450. // Depth Texture
  11451. if (this._webGLVersion > 1) {
  11452. this._caps.depthTextureExtension = true;
  11453. }
  11454. else {
  11455. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11456. if (depthTextureExtension != null) {
  11457. this._caps.depthTextureExtension = true;
  11458. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11459. }
  11460. }
  11461. // Vertex array object
  11462. if (this._webGLVersion > 1) {
  11463. this._caps.vertexArrayObject = true;
  11464. }
  11465. else {
  11466. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11467. if (vertexArrayObjectExtension != null) {
  11468. this._caps.vertexArrayObject = true;
  11469. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11470. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11471. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11472. }
  11473. else {
  11474. this._caps.vertexArrayObject = false;
  11475. }
  11476. }
  11477. // Instances count
  11478. if (this._webGLVersion > 1) {
  11479. this._caps.instancedArrays = true;
  11480. }
  11481. else {
  11482. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11483. if (instanceExtension != null) {
  11484. this._caps.instancedArrays = true;
  11485. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11486. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11487. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11488. }
  11489. else {
  11490. this._caps.instancedArrays = false;
  11491. }
  11492. }
  11493. // Intelligently add supported compressed formats in order to check for.
  11494. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11495. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11496. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11497. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11498. if (this._caps.astc)
  11499. this.texturesSupported.push('-astc.ktx');
  11500. if (this._caps.s3tc)
  11501. this.texturesSupported.push('-dxt.ktx');
  11502. if (this._caps.pvrtc)
  11503. this.texturesSupported.push('-pvrtc.ktx');
  11504. if (this._caps.etc2)
  11505. this.texturesSupported.push('-etc2.ktx');
  11506. if (this._caps.etc1)
  11507. this.texturesSupported.push('-etc1.ktx');
  11508. if (this._gl.getShaderPrecisionFormat) {
  11509. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11510. if (highp) {
  11511. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11512. }
  11513. }
  11514. // Depth buffer
  11515. this.setDepthBuffer(true);
  11516. this.setDepthFunctionToLessOrEqual();
  11517. this.setDepthWrite(true);
  11518. // Texture maps
  11519. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11520. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11521. this._nextFreeTextureSlots.push(slot);
  11522. }
  11523. };
  11524. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11525. get: function () {
  11526. return this._webGLVersion;
  11527. },
  11528. enumerable: true,
  11529. configurable: true
  11530. });
  11531. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11532. /**
  11533. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11534. */
  11535. get: function () {
  11536. return this._isStencilEnable;
  11537. },
  11538. enumerable: true,
  11539. configurable: true
  11540. });
  11541. Engine.prototype._prepareWorkingCanvas = function () {
  11542. if (this._workingCanvas) {
  11543. return;
  11544. }
  11545. this._workingCanvas = document.createElement("canvas");
  11546. var context = this._workingCanvas.getContext("2d");
  11547. if (context) {
  11548. this._workingContext = context;
  11549. }
  11550. };
  11551. Engine.prototype.resetTextureCache = function () {
  11552. for (var key in this._boundTexturesCache) {
  11553. var boundTexture = this._boundTexturesCache[key];
  11554. if (boundTexture) {
  11555. this._removeDesignatedSlot(boundTexture);
  11556. }
  11557. this._boundTexturesCache[key] = null;
  11558. }
  11559. if (!this.disableTextureBindingOptimization) {
  11560. this._nextFreeTextureSlots = [];
  11561. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11562. this._nextFreeTextureSlots.push(slot);
  11563. }
  11564. }
  11565. this._currentTextureChannel = -1;
  11566. };
  11567. Engine.prototype.isDeterministicLockStep = function () {
  11568. return this._deterministicLockstep;
  11569. };
  11570. Engine.prototype.getLockstepMaxSteps = function () {
  11571. return this._lockstepMaxSteps;
  11572. };
  11573. Engine.prototype.getGlInfo = function () {
  11574. return {
  11575. vendor: this._glVendor,
  11576. renderer: this._glRenderer,
  11577. version: this._glVersion
  11578. };
  11579. };
  11580. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11581. if (useScreen === void 0) { useScreen = false; }
  11582. var viewport = camera.viewport;
  11583. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11584. };
  11585. Engine.prototype.getRenderWidth = function (useScreen) {
  11586. if (useScreen === void 0) { useScreen = false; }
  11587. if (!useScreen && this._currentRenderTarget) {
  11588. return this._currentRenderTarget.width;
  11589. }
  11590. return this._gl.drawingBufferWidth;
  11591. };
  11592. Engine.prototype.getRenderHeight = function (useScreen) {
  11593. if (useScreen === void 0) { useScreen = false; }
  11594. if (!useScreen && this._currentRenderTarget) {
  11595. return this._currentRenderTarget.height;
  11596. }
  11597. return this._gl.drawingBufferHeight;
  11598. };
  11599. Engine.prototype.getRenderingCanvas = function () {
  11600. return this._renderingCanvas;
  11601. };
  11602. Engine.prototype.getRenderingCanvasClientRect = function () {
  11603. if (!this._renderingCanvas) {
  11604. return null;
  11605. }
  11606. return this._renderingCanvas.getBoundingClientRect();
  11607. };
  11608. Engine.prototype.setHardwareScalingLevel = function (level) {
  11609. this._hardwareScalingLevel = level;
  11610. this.resize();
  11611. };
  11612. Engine.prototype.getHardwareScalingLevel = function () {
  11613. return this._hardwareScalingLevel;
  11614. };
  11615. Engine.prototype.getLoadedTexturesCache = function () {
  11616. return this._internalTexturesCache;
  11617. };
  11618. Engine.prototype.getCaps = function () {
  11619. return this._caps;
  11620. };
  11621. Object.defineProperty(Engine.prototype, "drawCalls", {
  11622. /** The number of draw calls submitted last frame */
  11623. get: function () {
  11624. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11625. return 0;
  11626. },
  11627. enumerable: true,
  11628. configurable: true
  11629. });
  11630. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11631. get: function () {
  11632. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11633. return null;
  11634. },
  11635. enumerable: true,
  11636. configurable: true
  11637. });
  11638. Engine.prototype.getDepthFunction = function () {
  11639. return this._depthCullingState.depthFunc;
  11640. };
  11641. Engine.prototype.setDepthFunction = function (depthFunc) {
  11642. this._depthCullingState.depthFunc = depthFunc;
  11643. };
  11644. Engine.prototype.setDepthFunctionToGreater = function () {
  11645. this._depthCullingState.depthFunc = this._gl.GREATER;
  11646. };
  11647. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11648. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11649. };
  11650. Engine.prototype.setDepthFunctionToLess = function () {
  11651. this._depthCullingState.depthFunc = this._gl.LESS;
  11652. };
  11653. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11654. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11655. };
  11656. Engine.prototype.getStencilBuffer = function () {
  11657. return this._stencilState.stencilTest;
  11658. };
  11659. Engine.prototype.setStencilBuffer = function (enable) {
  11660. this._stencilState.stencilTest = enable;
  11661. };
  11662. Engine.prototype.getStencilMask = function () {
  11663. return this._stencilState.stencilMask;
  11664. };
  11665. Engine.prototype.setStencilMask = function (mask) {
  11666. this._stencilState.stencilMask = mask;
  11667. };
  11668. Engine.prototype.getStencilFunction = function () {
  11669. return this._stencilState.stencilFunc;
  11670. };
  11671. Engine.prototype.getStencilFunctionReference = function () {
  11672. return this._stencilState.stencilFuncRef;
  11673. };
  11674. Engine.prototype.getStencilFunctionMask = function () {
  11675. return this._stencilState.stencilFuncMask;
  11676. };
  11677. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11678. this._stencilState.stencilFunc = stencilFunc;
  11679. };
  11680. Engine.prototype.setStencilFunctionReference = function (reference) {
  11681. this._stencilState.stencilFuncRef = reference;
  11682. };
  11683. Engine.prototype.setStencilFunctionMask = function (mask) {
  11684. this._stencilState.stencilFuncMask = mask;
  11685. };
  11686. Engine.prototype.getStencilOperationFail = function () {
  11687. return this._stencilState.stencilOpStencilFail;
  11688. };
  11689. Engine.prototype.getStencilOperationDepthFail = function () {
  11690. return this._stencilState.stencilOpDepthFail;
  11691. };
  11692. Engine.prototype.getStencilOperationPass = function () {
  11693. return this._stencilState.stencilOpStencilDepthPass;
  11694. };
  11695. Engine.prototype.setStencilOperationFail = function (operation) {
  11696. this._stencilState.stencilOpStencilFail = operation;
  11697. };
  11698. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11699. this._stencilState.stencilOpDepthFail = operation;
  11700. };
  11701. Engine.prototype.setStencilOperationPass = function (operation) {
  11702. this._stencilState.stencilOpStencilDepthPass = operation;
  11703. };
  11704. Engine.prototype.setDitheringState = function (value) {
  11705. if (value) {
  11706. this._gl.enable(this._gl.DITHER);
  11707. }
  11708. else {
  11709. this._gl.disable(this._gl.DITHER);
  11710. }
  11711. };
  11712. Engine.prototype.setRasterizerState = function (value) {
  11713. if (value) {
  11714. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11715. }
  11716. else {
  11717. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11718. }
  11719. };
  11720. /**
  11721. * stop executing a render loop function and remove it from the execution array
  11722. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11723. */
  11724. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11725. if (!renderFunction) {
  11726. this._activeRenderLoops = [];
  11727. return;
  11728. }
  11729. var index = this._activeRenderLoops.indexOf(renderFunction);
  11730. if (index >= 0) {
  11731. this._activeRenderLoops.splice(index, 1);
  11732. }
  11733. };
  11734. Engine.prototype._renderLoop = function () {
  11735. if (!this._contextWasLost) {
  11736. var shouldRender = true;
  11737. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11738. shouldRender = false;
  11739. }
  11740. if (shouldRender) {
  11741. // Start new frame
  11742. this.beginFrame();
  11743. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11744. var renderFunction = this._activeRenderLoops[index];
  11745. renderFunction();
  11746. }
  11747. // Present
  11748. this.endFrame();
  11749. }
  11750. }
  11751. if (this._activeRenderLoops.length > 0) {
  11752. // Register new frame
  11753. var requester = null;
  11754. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11755. requester = this._vrDisplay;
  11756. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11757. }
  11758. else {
  11759. this._renderingQueueLaunched = false;
  11760. }
  11761. };
  11762. /**
  11763. * Register and execute a render loop. The engine can have more than one render function.
  11764. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11765. * @example
  11766. * engine.runRenderLoop(function () {
  11767. * scene.render()
  11768. * })
  11769. */
  11770. Engine.prototype.runRenderLoop = function (renderFunction) {
  11771. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11772. return;
  11773. }
  11774. this._activeRenderLoops.push(renderFunction);
  11775. if (!this._renderingQueueLaunched) {
  11776. this._renderingQueueLaunched = true;
  11777. this._bindedRenderFunction = this._renderLoop.bind(this);
  11778. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11779. }
  11780. };
  11781. /**
  11782. * Toggle full screen mode.
  11783. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11784. * @param {any} options - an options object to be sent to the requestFullscreen function
  11785. */
  11786. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11787. if (this.isFullscreen) {
  11788. BABYLON.Tools.ExitFullscreen();
  11789. }
  11790. else {
  11791. this._pointerLockRequested = requestPointerLock;
  11792. if (this._renderingCanvas) {
  11793. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11794. }
  11795. }
  11796. };
  11797. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11798. if (stencil === void 0) { stencil = false; }
  11799. this.applyStates();
  11800. var mode = 0;
  11801. if (backBuffer && color) {
  11802. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11803. mode |= this._gl.COLOR_BUFFER_BIT;
  11804. }
  11805. if (depth) {
  11806. this._gl.clearDepth(1.0);
  11807. mode |= this._gl.DEPTH_BUFFER_BIT;
  11808. }
  11809. if (stencil) {
  11810. this._gl.clearStencil(0);
  11811. mode |= this._gl.STENCIL_BUFFER_BIT;
  11812. }
  11813. this._gl.clear(mode);
  11814. };
  11815. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11816. var gl = this._gl;
  11817. // Save state
  11818. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11819. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11820. // Change state
  11821. gl.enable(gl.SCISSOR_TEST);
  11822. gl.scissor(x, y, width, height);
  11823. // Clear
  11824. this.clear(clearColor, true, true, true);
  11825. // Restore state
  11826. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11827. if (curScissor === true) {
  11828. gl.enable(gl.SCISSOR_TEST);
  11829. }
  11830. else {
  11831. gl.disable(gl.SCISSOR_TEST);
  11832. }
  11833. };
  11834. /**
  11835. * Set the WebGL's viewport
  11836. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11837. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11838. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11839. */
  11840. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11841. var width = requiredWidth || this.getRenderWidth();
  11842. var height = requiredHeight || this.getRenderHeight();
  11843. var x = viewport.x || 0;
  11844. var y = viewport.y || 0;
  11845. this._cachedViewport = viewport;
  11846. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11847. };
  11848. /**
  11849. * Directly set the WebGL Viewport
  11850. * The x, y, width & height are directly passed to the WebGL call
  11851. * @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.
  11852. */
  11853. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11854. var currentViewport = this._cachedViewport;
  11855. this._cachedViewport = null;
  11856. this._gl.viewport(x, y, width, height);
  11857. return currentViewport;
  11858. };
  11859. Engine.prototype.beginFrame = function () {
  11860. this.onBeginFrameObservable.notifyObservers(this);
  11861. this._measureFps();
  11862. };
  11863. Engine.prototype.endFrame = function () {
  11864. //force a flush in case we are using a bad OS.
  11865. if (this._badOS) {
  11866. this.flushFramebuffer();
  11867. }
  11868. //submit frame to the vr device, if enabled
  11869. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11870. // TODO: We should only submit the frame if we read frameData successfully.
  11871. this._vrDisplay.submitFrame();
  11872. }
  11873. this.onEndFrameObservable.notifyObservers(this);
  11874. };
  11875. /**
  11876. * resize the view according to the canvas' size.
  11877. * @example
  11878. * window.addEventListener("resize", function () {
  11879. * engine.resize();
  11880. * });
  11881. */
  11882. Engine.prototype.resize = function () {
  11883. // We're not resizing the size of the canvas while in VR mode & presenting
  11884. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11885. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11886. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11887. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11888. }
  11889. };
  11890. /**
  11891. * force a specific size of the canvas
  11892. * @param {number} width - the new canvas' width
  11893. * @param {number} height - the new canvas' height
  11894. */
  11895. Engine.prototype.setSize = function (width, height) {
  11896. if (!this._renderingCanvas) {
  11897. return;
  11898. }
  11899. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11900. return;
  11901. }
  11902. this._renderingCanvas.width = width;
  11903. this._renderingCanvas.height = height;
  11904. for (var index = 0; index < this.scenes.length; index++) {
  11905. var scene = this.scenes[index];
  11906. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11907. var cam = scene.cameras[camIndex];
  11908. cam._currentRenderId = 0;
  11909. }
  11910. }
  11911. if (this.onResizeObservable.hasObservers) {
  11912. this.onResizeObservable.notifyObservers(this);
  11913. }
  11914. };
  11915. // WebVR functions
  11916. Engine.prototype.isVRDevicePresent = function () {
  11917. return !!this._vrDisplay;
  11918. };
  11919. Engine.prototype.getVRDevice = function () {
  11920. return this._vrDisplay;
  11921. };
  11922. /**
  11923. * Initializes a webVR display and starts listening to display change events.
  11924. * The onVRDisplayChangedObservable will be notified upon these changes.
  11925. * @returns The onVRDisplayChangedObservable.
  11926. */
  11927. Engine.prototype.initWebVR = function () {
  11928. this.initWebVRAsync();
  11929. return this.onVRDisplayChangedObservable;
  11930. };
  11931. /**
  11932. * Initializes a webVR display and starts listening to display change events.
  11933. * The onVRDisplayChangedObservable will be notified upon these changes.
  11934. * @returns A promise containing a VRDisplay and if vr is supported.
  11935. */
  11936. Engine.prototype.initWebVRAsync = function () {
  11937. var _this = this;
  11938. var notifyObservers = function () {
  11939. var eventArgs = {
  11940. vrDisplay: _this._vrDisplay,
  11941. vrSupported: _this._vrSupported
  11942. };
  11943. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11944. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11945. };
  11946. if (!this._onVrDisplayConnect) {
  11947. this._onVrDisplayConnect = function (event) {
  11948. _this._vrDisplay = event.display;
  11949. notifyObservers();
  11950. };
  11951. this._onVrDisplayDisconnect = function () {
  11952. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11953. _this._vrDisplay = undefined;
  11954. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11955. notifyObservers();
  11956. };
  11957. this._onVrDisplayPresentChange = function () {
  11958. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11959. };
  11960. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11961. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11962. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11963. }
  11964. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11965. this._webVRInitPromise.then(notifyObservers);
  11966. return this._webVRInitPromise;
  11967. };
  11968. Engine.prototype.enableVR = function () {
  11969. var _this = this;
  11970. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11971. var onResolved = function () {
  11972. _this.onVRRequestPresentComplete.notifyObservers(true);
  11973. _this._onVRFullScreenTriggered();
  11974. };
  11975. var onRejected = function () {
  11976. _this.onVRRequestPresentComplete.notifyObservers(false);
  11977. };
  11978. this.onVRRequestPresentStart.notifyObservers(this);
  11979. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11980. }
  11981. };
  11982. Engine.prototype.disableVR = function () {
  11983. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11984. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11985. }
  11986. };
  11987. Engine.prototype._getVRDisplaysAsync = function () {
  11988. var _this = this;
  11989. return new Promise(function (res, rej) {
  11990. if (navigator.getVRDisplays) {
  11991. navigator.getVRDisplays().then(function (devices) {
  11992. _this._vrSupported = true;
  11993. // note that devices may actually be an empty array. This is fine;
  11994. // we expect this._vrDisplay to be undefined in this case.
  11995. _this._vrDisplay = devices[0];
  11996. res({
  11997. vrDisplay: _this._vrDisplay,
  11998. vrSupported: _this._vrSupported
  11999. });
  12000. });
  12001. }
  12002. else {
  12003. _this._vrDisplay = undefined;
  12004. _this._vrSupported = false;
  12005. res({
  12006. vrDisplay: _this._vrDisplay,
  12007. vrSupported: _this._vrSupported
  12008. });
  12009. }
  12010. });
  12011. };
  12012. /**
  12013. * Binds the frame buffer to the specified texture.
  12014. * @param texture The texture to render to or null for the default canvas
  12015. * @param faceIndex The face of the texture to render to in case of cube texture
  12016. * @param requiredWidth The width of the target to render to
  12017. * @param requiredHeight The height of the target to render to
  12018. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12019. * @param depthStencilTexture The depth stencil texture to use to render
  12020. */
  12021. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  12022. if (this._currentRenderTarget) {
  12023. this.unBindFramebuffer(this._currentRenderTarget);
  12024. }
  12025. this._currentRenderTarget = texture;
  12026. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12027. var gl = this._gl;
  12028. if (texture.isCube) {
  12029. if (faceIndex === undefined) {
  12030. faceIndex = 0;
  12031. }
  12032. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12033. if (depthStencilTexture) {
  12034. if (depthStencilTexture._generateStencilBuffer) {
  12035. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12036. }
  12037. else {
  12038. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12039. }
  12040. }
  12041. }
  12042. if (this._cachedViewport && !forceFullscreenViewport) {
  12043. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12044. }
  12045. else {
  12046. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  12047. }
  12048. this.wipeCaches();
  12049. };
  12050. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12051. if (this._currentFramebuffer !== framebuffer) {
  12052. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12053. this._currentFramebuffer = framebuffer;
  12054. }
  12055. };
  12056. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12057. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12058. this._currentRenderTarget = null;
  12059. // If MSAA, we need to bitblt back to main texture
  12060. var gl = this._gl;
  12061. if (texture._MSAAFramebuffer) {
  12062. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12063. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12064. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12065. }
  12066. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12067. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12068. gl.generateMipmap(gl.TEXTURE_2D);
  12069. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12070. }
  12071. if (onBeforeUnbind) {
  12072. if (texture._MSAAFramebuffer) {
  12073. // Bind the correct framebuffer
  12074. this.bindUnboundFramebuffer(texture._framebuffer);
  12075. }
  12076. onBeforeUnbind();
  12077. }
  12078. this.bindUnboundFramebuffer(null);
  12079. };
  12080. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12081. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12082. this._currentRenderTarget = null;
  12083. // If MSAA, we need to bitblt back to main texture
  12084. var gl = this._gl;
  12085. if (textures[0]._MSAAFramebuffer) {
  12086. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12087. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12088. var attachments = textures[0]._attachments;
  12089. if (!attachments) {
  12090. attachments = new Array(textures.length);
  12091. textures[0]._attachments = attachments;
  12092. }
  12093. for (var i = 0; i < textures.length; i++) {
  12094. var texture = textures[i];
  12095. for (var j = 0; j < attachments.length; j++) {
  12096. attachments[j] = gl.NONE;
  12097. }
  12098. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12099. gl.readBuffer(attachments[i]);
  12100. gl.drawBuffers(attachments);
  12101. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12102. }
  12103. for (var i = 0; i < attachments.length; i++) {
  12104. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12105. }
  12106. gl.drawBuffers(attachments);
  12107. }
  12108. for (var i = 0; i < textures.length; i++) {
  12109. var texture = textures[i];
  12110. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12111. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12112. gl.generateMipmap(gl.TEXTURE_2D);
  12113. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12114. }
  12115. }
  12116. if (onBeforeUnbind) {
  12117. if (textures[0]._MSAAFramebuffer) {
  12118. // Bind the correct framebuffer
  12119. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12120. }
  12121. onBeforeUnbind();
  12122. }
  12123. this.bindUnboundFramebuffer(null);
  12124. };
  12125. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12126. if (texture.generateMipMaps) {
  12127. var gl = this._gl;
  12128. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12129. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12130. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12131. }
  12132. };
  12133. Engine.prototype.flushFramebuffer = function () {
  12134. this._gl.flush();
  12135. };
  12136. Engine.prototype.restoreDefaultFramebuffer = function () {
  12137. if (this._currentRenderTarget) {
  12138. this.unBindFramebuffer(this._currentRenderTarget);
  12139. }
  12140. else {
  12141. this.bindUnboundFramebuffer(null);
  12142. }
  12143. if (this._cachedViewport) {
  12144. this.setViewport(this._cachedViewport);
  12145. }
  12146. this.wipeCaches();
  12147. };
  12148. // UBOs
  12149. Engine.prototype.createUniformBuffer = function (elements) {
  12150. var ubo = this._gl.createBuffer();
  12151. if (!ubo) {
  12152. throw new Error("Unable to create uniform buffer");
  12153. }
  12154. this.bindUniformBuffer(ubo);
  12155. if (elements instanceof Float32Array) {
  12156. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12157. }
  12158. else {
  12159. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12160. }
  12161. this.bindUniformBuffer(null);
  12162. ubo.references = 1;
  12163. return ubo;
  12164. };
  12165. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12166. var ubo = this._gl.createBuffer();
  12167. if (!ubo) {
  12168. throw new Error("Unable to create dynamic uniform buffer");
  12169. }
  12170. this.bindUniformBuffer(ubo);
  12171. if (elements instanceof Float32Array) {
  12172. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12173. }
  12174. else {
  12175. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12176. }
  12177. this.bindUniformBuffer(null);
  12178. ubo.references = 1;
  12179. return ubo;
  12180. };
  12181. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12182. this.bindUniformBuffer(uniformBuffer);
  12183. if (offset === undefined) {
  12184. offset = 0;
  12185. }
  12186. if (count === undefined) {
  12187. if (elements instanceof Float32Array) {
  12188. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12189. }
  12190. else {
  12191. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12192. }
  12193. }
  12194. else {
  12195. if (elements instanceof Float32Array) {
  12196. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12197. }
  12198. else {
  12199. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12200. }
  12201. }
  12202. this.bindUniformBuffer(null);
  12203. };
  12204. // VBOs
  12205. Engine.prototype._resetVertexBufferBinding = function () {
  12206. this.bindArrayBuffer(null);
  12207. this._cachedVertexBuffers = null;
  12208. };
  12209. Engine.prototype.createVertexBuffer = function (vertices) {
  12210. var vbo = this._gl.createBuffer();
  12211. if (!vbo) {
  12212. throw new Error("Unable to create vertex buffer");
  12213. }
  12214. this.bindArrayBuffer(vbo);
  12215. if (vertices instanceof Float32Array) {
  12216. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  12217. }
  12218. else {
  12219. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  12220. }
  12221. this._resetVertexBufferBinding();
  12222. vbo.references = 1;
  12223. return vbo;
  12224. };
  12225. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  12226. var vbo = this._gl.createBuffer();
  12227. if (!vbo) {
  12228. throw new Error("Unable to create dynamic vertex buffer");
  12229. }
  12230. this.bindArrayBuffer(vbo);
  12231. if (vertices instanceof Float32Array) {
  12232. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  12233. }
  12234. else {
  12235. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  12236. }
  12237. this._resetVertexBufferBinding();
  12238. vbo.references = 1;
  12239. return vbo;
  12240. };
  12241. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12242. if (offset === void 0) { offset = 0; }
  12243. // Force cache update
  12244. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12245. this.bindIndexBuffer(indexBuffer);
  12246. var arrayBuffer;
  12247. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12248. arrayBuffer = indices;
  12249. }
  12250. else {
  12251. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12252. }
  12253. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12254. this._resetIndexBufferBinding();
  12255. };
  12256. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12257. this.bindArrayBuffer(vertexBuffer);
  12258. if (offset === undefined) {
  12259. offset = 0;
  12260. }
  12261. if (count === undefined) {
  12262. if (vertices instanceof Float32Array) {
  12263. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12264. }
  12265. else {
  12266. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12267. }
  12268. }
  12269. else {
  12270. if (vertices instanceof Float32Array) {
  12271. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12272. }
  12273. else {
  12274. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12275. }
  12276. }
  12277. this._resetVertexBufferBinding();
  12278. };
  12279. Engine.prototype._resetIndexBufferBinding = function () {
  12280. this.bindIndexBuffer(null);
  12281. this._cachedIndexBuffer = null;
  12282. };
  12283. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12284. var vbo = this._gl.createBuffer();
  12285. if (!vbo) {
  12286. throw new Error("Unable to create index buffer");
  12287. }
  12288. this.bindIndexBuffer(vbo);
  12289. // Check for 32 bits indices
  12290. var arrayBuffer;
  12291. var need32Bits = false;
  12292. if (indices instanceof Uint16Array) {
  12293. arrayBuffer = indices;
  12294. }
  12295. else {
  12296. //check 32 bit support
  12297. if (this._caps.uintIndices) {
  12298. if (indices instanceof Uint32Array) {
  12299. arrayBuffer = indices;
  12300. need32Bits = true;
  12301. }
  12302. else {
  12303. //number[] or Int32Array, check if 32 bit is necessary
  12304. for (var index = 0; index < indices.length; index++) {
  12305. if (indices[index] > 65535) {
  12306. need32Bits = true;
  12307. break;
  12308. }
  12309. }
  12310. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12311. }
  12312. }
  12313. else {
  12314. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12315. arrayBuffer = new Uint16Array(indices);
  12316. }
  12317. }
  12318. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12319. this._resetIndexBufferBinding();
  12320. vbo.references = 1;
  12321. vbo.is32Bits = need32Bits;
  12322. return vbo;
  12323. };
  12324. Engine.prototype.bindArrayBuffer = function (buffer) {
  12325. if (!this._vaoRecordInProgress) {
  12326. this._unbindVertexArrayObject();
  12327. }
  12328. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12329. };
  12330. Engine.prototype.bindUniformBuffer = function (buffer) {
  12331. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12332. };
  12333. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12334. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12335. };
  12336. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12337. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12338. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12339. };
  12340. ;
  12341. Engine.prototype.bindIndexBuffer = function (buffer) {
  12342. if (!this._vaoRecordInProgress) {
  12343. this._unbindVertexArrayObject();
  12344. }
  12345. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12346. };
  12347. Engine.prototype.bindBuffer = function (buffer, target) {
  12348. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12349. this._gl.bindBuffer(target, buffer);
  12350. this._currentBoundBuffer[target] = buffer;
  12351. }
  12352. };
  12353. Engine.prototype.updateArrayBuffer = function (data) {
  12354. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12355. };
  12356. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12357. var pointer = this._currentBufferPointers[indx];
  12358. var changed = false;
  12359. if (!pointer.active) {
  12360. changed = true;
  12361. pointer.active = true;
  12362. pointer.index = indx;
  12363. pointer.size = size;
  12364. pointer.type = type;
  12365. pointer.normalized = normalized;
  12366. pointer.stride = stride;
  12367. pointer.offset = offset;
  12368. pointer.buffer = buffer;
  12369. }
  12370. else {
  12371. if (pointer.buffer !== buffer) {
  12372. pointer.buffer = buffer;
  12373. changed = true;
  12374. }
  12375. if (pointer.size !== size) {
  12376. pointer.size = size;
  12377. changed = true;
  12378. }
  12379. if (pointer.type !== type) {
  12380. pointer.type = type;
  12381. changed = true;
  12382. }
  12383. if (pointer.normalized !== normalized) {
  12384. pointer.normalized = normalized;
  12385. changed = true;
  12386. }
  12387. if (pointer.stride !== stride) {
  12388. pointer.stride = stride;
  12389. changed = true;
  12390. }
  12391. if (pointer.offset !== offset) {
  12392. pointer.offset = offset;
  12393. changed = true;
  12394. }
  12395. }
  12396. if (changed || this._vaoRecordInProgress) {
  12397. this.bindArrayBuffer(buffer);
  12398. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12399. }
  12400. };
  12401. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12402. if (indexBuffer == null) {
  12403. return;
  12404. }
  12405. if (this._cachedIndexBuffer !== indexBuffer) {
  12406. this._cachedIndexBuffer = indexBuffer;
  12407. this.bindIndexBuffer(indexBuffer);
  12408. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12409. }
  12410. };
  12411. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12412. var attributes = effect.getAttributesNames();
  12413. if (!this._vaoRecordInProgress) {
  12414. this._unbindVertexArrayObject();
  12415. }
  12416. this.unbindAllAttributes();
  12417. for (var index = 0; index < attributes.length; index++) {
  12418. var order = effect.getAttributeLocation(index);
  12419. if (order >= 0) {
  12420. var vertexBuffer = vertexBuffers[attributes[index]];
  12421. if (!vertexBuffer) {
  12422. continue;
  12423. }
  12424. this._gl.enableVertexAttribArray(order);
  12425. if (!this._vaoRecordInProgress) {
  12426. this._vertexAttribArraysEnabled[order] = true;
  12427. }
  12428. var buffer = vertexBuffer.getBuffer();
  12429. if (buffer) {
  12430. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12431. if (vertexBuffer.getIsInstanced()) {
  12432. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12433. if (!this._vaoRecordInProgress) {
  12434. this._currentInstanceLocations.push(order);
  12435. this._currentInstanceBuffers.push(buffer);
  12436. }
  12437. }
  12438. }
  12439. }
  12440. }
  12441. };
  12442. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12443. var vao = this._gl.createVertexArray();
  12444. this._vaoRecordInProgress = true;
  12445. this._gl.bindVertexArray(vao);
  12446. this._mustWipeVertexAttributes = true;
  12447. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12448. this.bindIndexBuffer(indexBuffer);
  12449. this._vaoRecordInProgress = false;
  12450. this._gl.bindVertexArray(null);
  12451. return vao;
  12452. };
  12453. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12454. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12455. this._cachedVertexArrayObject = vertexArrayObject;
  12456. this._gl.bindVertexArray(vertexArrayObject);
  12457. this._cachedVertexBuffers = null;
  12458. this._cachedIndexBuffer = null;
  12459. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12460. this._mustWipeVertexAttributes = true;
  12461. }
  12462. };
  12463. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12464. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12465. this._cachedVertexBuffers = vertexBuffer;
  12466. this._cachedEffectForVertexBuffers = effect;
  12467. var attributesCount = effect.getAttributesCount();
  12468. this._unbindVertexArrayObject();
  12469. this.unbindAllAttributes();
  12470. var offset = 0;
  12471. for (var index = 0; index < attributesCount; index++) {
  12472. if (index < vertexDeclaration.length) {
  12473. var order = effect.getAttributeLocation(index);
  12474. if (order >= 0) {
  12475. this._gl.enableVertexAttribArray(order);
  12476. this._vertexAttribArraysEnabled[order] = true;
  12477. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12478. }
  12479. offset += vertexDeclaration[index] * 4;
  12480. }
  12481. }
  12482. }
  12483. this._bindIndexBufferWithCache(indexBuffer);
  12484. };
  12485. Engine.prototype._unbindVertexArrayObject = function () {
  12486. if (!this._cachedVertexArrayObject) {
  12487. return;
  12488. }
  12489. this._cachedVertexArrayObject = null;
  12490. this._gl.bindVertexArray(null);
  12491. };
  12492. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12493. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12494. this._cachedVertexBuffers = vertexBuffers;
  12495. this._cachedEffectForVertexBuffers = effect;
  12496. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12497. }
  12498. this._bindIndexBufferWithCache(indexBuffer);
  12499. };
  12500. Engine.prototype.unbindInstanceAttributes = function () {
  12501. var boundBuffer;
  12502. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12503. var instancesBuffer = this._currentInstanceBuffers[i];
  12504. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12505. boundBuffer = instancesBuffer;
  12506. this.bindArrayBuffer(instancesBuffer);
  12507. }
  12508. var offsetLocation = this._currentInstanceLocations[i];
  12509. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12510. }
  12511. this._currentInstanceBuffers.length = 0;
  12512. this._currentInstanceLocations.length = 0;
  12513. };
  12514. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12515. this._gl.deleteVertexArray(vao);
  12516. };
  12517. Engine.prototype._releaseBuffer = function (buffer) {
  12518. buffer.references--;
  12519. if (buffer.references === 0) {
  12520. this._gl.deleteBuffer(buffer);
  12521. return true;
  12522. }
  12523. return false;
  12524. };
  12525. Engine.prototype.createInstancesBuffer = function (capacity) {
  12526. var buffer = this._gl.createBuffer();
  12527. if (!buffer) {
  12528. throw new Error("Unable to create instance buffer");
  12529. }
  12530. buffer.capacity = capacity;
  12531. this.bindArrayBuffer(buffer);
  12532. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12533. return buffer;
  12534. };
  12535. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12536. this._gl.deleteBuffer(buffer);
  12537. };
  12538. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12539. this.bindArrayBuffer(instancesBuffer);
  12540. if (data) {
  12541. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12542. }
  12543. if (offsetLocations[0].index !== undefined) {
  12544. var stride = 0;
  12545. for (var i = 0; i < offsetLocations.length; i++) {
  12546. var ai = offsetLocations[i];
  12547. stride += ai.attributeSize * 4;
  12548. }
  12549. for (var i = 0; i < offsetLocations.length; i++) {
  12550. var ai = offsetLocations[i];
  12551. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12552. this._gl.enableVertexAttribArray(ai.index);
  12553. this._vertexAttribArraysEnabled[ai.index] = true;
  12554. }
  12555. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12556. this._gl.vertexAttribDivisor(ai.index, 1);
  12557. this._currentInstanceLocations.push(ai.index);
  12558. this._currentInstanceBuffers.push(instancesBuffer);
  12559. }
  12560. }
  12561. else {
  12562. for (var index = 0; index < 4; index++) {
  12563. var offsetLocation = offsetLocations[index];
  12564. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12565. this._gl.enableVertexAttribArray(offsetLocation);
  12566. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12567. }
  12568. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12569. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12570. this._currentInstanceLocations.push(offsetLocation);
  12571. this._currentInstanceBuffers.push(instancesBuffer);
  12572. }
  12573. }
  12574. };
  12575. Engine.prototype.applyStates = function () {
  12576. this._depthCullingState.apply(this._gl);
  12577. this._stencilState.apply(this._gl);
  12578. this._alphaState.apply(this._gl);
  12579. };
  12580. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12581. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12582. };
  12583. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12584. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12585. };
  12586. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12587. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12588. };
  12589. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12590. // Apply states
  12591. this.applyStates();
  12592. this._drawCalls.addCount(1, false);
  12593. // Render
  12594. var drawMode = this._drawMode(fillMode);
  12595. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12596. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12597. if (instancesCount) {
  12598. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12599. }
  12600. else {
  12601. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12602. }
  12603. };
  12604. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12605. // Apply states
  12606. this.applyStates();
  12607. this._drawCalls.addCount(1, false);
  12608. var drawMode = this._drawMode(fillMode);
  12609. if (instancesCount) {
  12610. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12611. }
  12612. else {
  12613. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12614. }
  12615. };
  12616. Engine.prototype._drawMode = function (fillMode) {
  12617. switch (fillMode) {
  12618. // Triangle views
  12619. case BABYLON.Material.TriangleFillMode:
  12620. return this._gl.TRIANGLES;
  12621. case BABYLON.Material.PointFillMode:
  12622. return this._gl.POINTS;
  12623. case BABYLON.Material.WireFrameFillMode:
  12624. return this._gl.LINES;
  12625. // Draw modes
  12626. case BABYLON.Material.PointListDrawMode:
  12627. return this._gl.POINTS;
  12628. case BABYLON.Material.LineListDrawMode:
  12629. return this._gl.LINES;
  12630. case BABYLON.Material.LineLoopDrawMode:
  12631. return this._gl.LINE_LOOP;
  12632. case BABYLON.Material.LineStripDrawMode:
  12633. return this._gl.LINE_STRIP;
  12634. case BABYLON.Material.TriangleStripDrawMode:
  12635. return this._gl.TRIANGLE_STRIP;
  12636. case BABYLON.Material.TriangleFanDrawMode:
  12637. return this._gl.TRIANGLE_FAN;
  12638. default:
  12639. return this._gl.TRIANGLES;
  12640. }
  12641. };
  12642. // Shaders
  12643. Engine.prototype._releaseEffect = function (effect) {
  12644. if (this._compiledEffects[effect._key]) {
  12645. delete this._compiledEffects[effect._key];
  12646. this._deleteProgram(effect.getProgram());
  12647. }
  12648. };
  12649. Engine.prototype._deleteProgram = function (program) {
  12650. if (program) {
  12651. program.__SPECTOR_rebuildProgram = null;
  12652. if (program.transformFeedback) {
  12653. this.deleteTransformFeedback(program.transformFeedback);
  12654. program.transformFeedback = null;
  12655. }
  12656. this._gl.deleteProgram(program);
  12657. }
  12658. };
  12659. /**
  12660. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12661. * @param samplers An array of string used to represent textures
  12662. */
  12663. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12664. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12665. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12666. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12667. if (this._compiledEffects[name]) {
  12668. var compiledEffect = this._compiledEffects[name];
  12669. if (onCompiled && compiledEffect.isReady()) {
  12670. onCompiled(compiledEffect);
  12671. }
  12672. return compiledEffect;
  12673. }
  12674. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12675. effect._key = name;
  12676. this._compiledEffects[name] = effect;
  12677. return effect;
  12678. };
  12679. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12680. if (uniformsNames === void 0) { uniformsNames = []; }
  12681. if (samplers === void 0) { samplers = []; }
  12682. if (defines === void 0) { defines = ""; }
  12683. return this.createEffect({
  12684. vertex: "particles",
  12685. fragmentElement: fragmentName
  12686. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12687. };
  12688. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12689. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12690. context = context || this._gl;
  12691. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12692. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12693. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12694. };
  12695. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12696. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12697. context = context || this._gl;
  12698. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12699. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  12700. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12701. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12702. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12703. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12704. return program;
  12705. };
  12706. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12707. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12708. var shaderProgram = context.createProgram();
  12709. if (!shaderProgram) {
  12710. throw new Error("Unable to create program");
  12711. }
  12712. context.attachShader(shaderProgram, vertexShader);
  12713. context.attachShader(shaderProgram, fragmentShader);
  12714. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12715. var transformFeedback = this.createTransformFeedback();
  12716. this.bindTransformFeedback(transformFeedback);
  12717. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12718. shaderProgram.transformFeedback = transformFeedback;
  12719. }
  12720. context.linkProgram(shaderProgram);
  12721. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12722. this.bindTransformFeedback(null);
  12723. }
  12724. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12725. if (!linked) {
  12726. context.validateProgram(shaderProgram);
  12727. var error = context.getProgramInfoLog(shaderProgram);
  12728. if (error) {
  12729. throw new Error(error);
  12730. }
  12731. }
  12732. context.deleteShader(vertexShader);
  12733. context.deleteShader(fragmentShader);
  12734. return shaderProgram;
  12735. };
  12736. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12737. var results = new Array();
  12738. for (var index = 0; index < uniformsNames.length; index++) {
  12739. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12740. }
  12741. return results;
  12742. };
  12743. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12744. var results = [];
  12745. for (var index = 0; index < attributesNames.length; index++) {
  12746. try {
  12747. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12748. }
  12749. catch (e) {
  12750. results.push(-1);
  12751. }
  12752. }
  12753. return results;
  12754. };
  12755. Engine.prototype.enableEffect = function (effect) {
  12756. if (!effect) {
  12757. return;
  12758. }
  12759. // Use program
  12760. this.bindSamplers(effect);
  12761. this._currentEffect = effect;
  12762. if (effect.onBind) {
  12763. effect.onBind(effect);
  12764. }
  12765. effect.onBindObservable.notifyObservers(effect);
  12766. };
  12767. Engine.prototype.setIntArray = function (uniform, array) {
  12768. if (!uniform)
  12769. return;
  12770. this._gl.uniform1iv(uniform, array);
  12771. };
  12772. Engine.prototype.setIntArray2 = function (uniform, array) {
  12773. if (!uniform || array.length % 2 !== 0)
  12774. return;
  12775. this._gl.uniform2iv(uniform, array);
  12776. };
  12777. Engine.prototype.setIntArray3 = function (uniform, array) {
  12778. if (!uniform || array.length % 3 !== 0)
  12779. return;
  12780. this._gl.uniform3iv(uniform, array);
  12781. };
  12782. Engine.prototype.setIntArray4 = function (uniform, array) {
  12783. if (!uniform || array.length % 4 !== 0)
  12784. return;
  12785. this._gl.uniform4iv(uniform, array);
  12786. };
  12787. Engine.prototype.setFloatArray = function (uniform, array) {
  12788. if (!uniform)
  12789. return;
  12790. this._gl.uniform1fv(uniform, array);
  12791. };
  12792. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12793. if (!uniform || array.length % 2 !== 0)
  12794. return;
  12795. this._gl.uniform2fv(uniform, array);
  12796. };
  12797. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12798. if (!uniform || array.length % 3 !== 0)
  12799. return;
  12800. this._gl.uniform3fv(uniform, array);
  12801. };
  12802. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12803. if (!uniform || array.length % 4 !== 0)
  12804. return;
  12805. this._gl.uniform4fv(uniform, array);
  12806. };
  12807. Engine.prototype.setArray = function (uniform, array) {
  12808. if (!uniform)
  12809. return;
  12810. this._gl.uniform1fv(uniform, array);
  12811. };
  12812. Engine.prototype.setArray2 = function (uniform, array) {
  12813. if (!uniform || array.length % 2 !== 0)
  12814. return;
  12815. this._gl.uniform2fv(uniform, array);
  12816. };
  12817. Engine.prototype.setArray3 = function (uniform, array) {
  12818. if (!uniform || array.length % 3 !== 0)
  12819. return;
  12820. this._gl.uniform3fv(uniform, array);
  12821. };
  12822. Engine.prototype.setArray4 = function (uniform, array) {
  12823. if (!uniform || array.length % 4 !== 0)
  12824. return;
  12825. this._gl.uniform4fv(uniform, array);
  12826. };
  12827. Engine.prototype.setMatrices = function (uniform, matrices) {
  12828. if (!uniform)
  12829. return;
  12830. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12831. };
  12832. Engine.prototype.setMatrix = function (uniform, matrix) {
  12833. if (!uniform)
  12834. return;
  12835. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12836. };
  12837. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12838. if (!uniform)
  12839. return;
  12840. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12841. };
  12842. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12843. if (!uniform)
  12844. return;
  12845. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12846. };
  12847. Engine.prototype.setInt = function (uniform, value) {
  12848. if (!uniform)
  12849. return;
  12850. this._gl.uniform1i(uniform, value);
  12851. };
  12852. Engine.prototype.setFloat = function (uniform, value) {
  12853. if (!uniform)
  12854. return;
  12855. this._gl.uniform1f(uniform, value);
  12856. };
  12857. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12858. if (!uniform)
  12859. return;
  12860. this._gl.uniform2f(uniform, x, y);
  12861. };
  12862. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12863. if (!uniform)
  12864. return;
  12865. this._gl.uniform3f(uniform, x, y, z);
  12866. };
  12867. Engine.prototype.setBool = function (uniform, bool) {
  12868. if (!uniform)
  12869. return;
  12870. this._gl.uniform1i(uniform, bool);
  12871. };
  12872. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12873. if (!uniform)
  12874. return;
  12875. this._gl.uniform4f(uniform, x, y, z, w);
  12876. };
  12877. Engine.prototype.setColor3 = function (uniform, color3) {
  12878. if (!uniform)
  12879. return;
  12880. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12881. };
  12882. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12883. if (!uniform)
  12884. return;
  12885. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12886. };
  12887. /**
  12888. * Sets a Color4 on a uniform variable
  12889. * @param uniform defines the uniform location
  12890. * @param color4 defines the value to be set
  12891. */
  12892. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12893. if (!uniform)
  12894. return;
  12895. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12896. };
  12897. // States
  12898. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12899. if (zOffset === void 0) { zOffset = 0; }
  12900. if (reverseSide === void 0) { reverseSide = false; }
  12901. // Culling
  12902. if (this._depthCullingState.cull !== culling || force) {
  12903. this._depthCullingState.cull = culling;
  12904. }
  12905. // Cull face
  12906. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12907. if (this._depthCullingState.cullFace !== cullFace || force) {
  12908. this._depthCullingState.cullFace = cullFace;
  12909. }
  12910. // Z offset
  12911. this.setZOffset(zOffset);
  12912. // Front face
  12913. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12914. if (this._depthCullingState.frontFace !== frontFace || force) {
  12915. this._depthCullingState.frontFace = frontFace;
  12916. }
  12917. };
  12918. Engine.prototype.setZOffset = function (value) {
  12919. this._depthCullingState.zOffset = value;
  12920. };
  12921. Engine.prototype.getZOffset = function () {
  12922. return this._depthCullingState.zOffset;
  12923. };
  12924. Engine.prototype.setDepthBuffer = function (enable) {
  12925. this._depthCullingState.depthTest = enable;
  12926. };
  12927. Engine.prototype.getDepthWrite = function () {
  12928. return this._depthCullingState.depthMask;
  12929. };
  12930. Engine.prototype.setDepthWrite = function (enable) {
  12931. this._depthCullingState.depthMask = enable;
  12932. };
  12933. Engine.prototype.setColorWrite = function (enable) {
  12934. this._gl.colorMask(enable, enable, enable, enable);
  12935. this._colorWrite = enable;
  12936. };
  12937. Engine.prototype.getColorWrite = function () {
  12938. return this._colorWrite;
  12939. };
  12940. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12941. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12942. };
  12943. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12944. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12945. if (this._alphaMode === mode) {
  12946. return;
  12947. }
  12948. switch (mode) {
  12949. case Engine.ALPHA_DISABLE:
  12950. this._alphaState.alphaBlend = false;
  12951. break;
  12952. case Engine.ALPHA_PREMULTIPLIED:
  12953. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12954. this._alphaState.alphaBlend = true;
  12955. break;
  12956. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12957. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12958. this._alphaState.alphaBlend = true;
  12959. break;
  12960. case Engine.ALPHA_COMBINE:
  12961. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12962. this._alphaState.alphaBlend = true;
  12963. break;
  12964. case Engine.ALPHA_ONEONE:
  12965. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12966. this._alphaState.alphaBlend = true;
  12967. break;
  12968. case Engine.ALPHA_ADD:
  12969. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12970. this._alphaState.alphaBlend = true;
  12971. break;
  12972. case Engine.ALPHA_SUBTRACT:
  12973. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12974. this._alphaState.alphaBlend = true;
  12975. break;
  12976. case Engine.ALPHA_MULTIPLY:
  12977. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12978. this._alphaState.alphaBlend = true;
  12979. break;
  12980. case Engine.ALPHA_MAXIMIZED:
  12981. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12982. this._alphaState.alphaBlend = true;
  12983. break;
  12984. case Engine.ALPHA_INTERPOLATE:
  12985. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12986. this._alphaState.alphaBlend = true;
  12987. break;
  12988. case Engine.ALPHA_SCREENMODE:
  12989. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12990. this._alphaState.alphaBlend = true;
  12991. break;
  12992. }
  12993. if (!noDepthWriteChange) {
  12994. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12995. }
  12996. this._alphaMode = mode;
  12997. };
  12998. Engine.prototype.getAlphaMode = function () {
  12999. return this._alphaMode;
  13000. };
  13001. // Textures
  13002. Engine.prototype.wipeCaches = function (bruteForce) {
  13003. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  13004. return;
  13005. }
  13006. this._currentEffect = null;
  13007. // 6/8/2017: deltakosh: Should not be required anymore.
  13008. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  13009. if (bruteForce) {
  13010. this.resetTextureCache();
  13011. this._currentProgram = null;
  13012. this._stencilState.reset();
  13013. this._depthCullingState.reset();
  13014. this.setDepthFunctionToLessOrEqual();
  13015. this._alphaState.reset();
  13016. }
  13017. this._resetVertexBufferBinding();
  13018. this._cachedIndexBuffer = null;
  13019. this._cachedEffectForVertexBuffers = null;
  13020. this._unbindVertexArrayObject();
  13021. this.bindIndexBuffer(null);
  13022. };
  13023. /**
  13024. * Set the compressed texture format to use, based on the formats you have, and the formats
  13025. * supported by the hardware / browser.
  13026. *
  13027. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  13028. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  13029. * to API arguments needed to compressed textures. This puts the burden on the container
  13030. * generator to house the arcane code for determining these for current & future formats.
  13031. *
  13032. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  13033. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  13034. *
  13035. * Note: The result of this call is not taken into account when a texture is base64.
  13036. *
  13037. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  13038. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  13039. *
  13040. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  13041. * @returns The extension selected.
  13042. */
  13043. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  13044. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  13045. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  13046. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  13047. return this._textureFormatInUse = this._texturesSupported[i];
  13048. }
  13049. }
  13050. }
  13051. // actively set format to nothing, to allow this to be called more than once
  13052. // and possibly fail the 2nd time
  13053. this._textureFormatInUse = null;
  13054. return null;
  13055. };
  13056. Engine.prototype._createTexture = function () {
  13057. var texture = this._gl.createTexture();
  13058. if (!texture) {
  13059. throw new Error("Unable to create texture");
  13060. }
  13061. return texture;
  13062. };
  13063. /**
  13064. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  13065. * @param {string} urlArg- This contains one of the following:
  13066. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  13067. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  13068. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  13069. *
  13070. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  13071. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  13072. * @param {Scene} scene- Needed for loading to the correct scene.
  13073. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  13074. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  13075. * @param {callback} onError- Optional callback to be called upon failure.
  13076. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  13077. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  13078. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  13079. *
  13080. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  13081. */
  13082. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  13083. var _this = this;
  13084. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13085. if (onLoad === void 0) { onLoad = null; }
  13086. if (onError === void 0) { onError = null; }
  13087. if (buffer === void 0) { buffer = null; }
  13088. if (fallBack === void 0) { fallBack = null; }
  13089. if (format === void 0) { format = null; }
  13090. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  13091. var fromData = url.substr(0, 5) === "data:";
  13092. var fromBlob = url.substr(0, 5) === "blob:";
  13093. var isBase64 = fromData && url.indexOf("base64") !== -1;
  13094. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  13095. // establish the file extension, if possible
  13096. var lastDot = url.lastIndexOf('.');
  13097. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  13098. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  13099. var isTGA = (extension.indexOf(".tga") === 0);
  13100. // determine if a ktx file should be substituted
  13101. var isKTX = false;
  13102. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  13103. url = url.substring(0, lastDot) + this._textureFormatInUse;
  13104. isKTX = true;
  13105. }
  13106. if (scene) {
  13107. scene._addPendingData(texture);
  13108. }
  13109. texture.url = url;
  13110. texture.generateMipMaps = !noMipmap;
  13111. texture.samplingMode = samplingMode;
  13112. texture.invertY = invertY;
  13113. if (!this._doNotHandleContextLost) {
  13114. // Keep a link to the buffer only if we plan to handle context lost
  13115. texture._buffer = buffer;
  13116. }
  13117. var onLoadObserver = null;
  13118. if (onLoad && !fallBack) {
  13119. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  13120. }
  13121. if (!fallBack)
  13122. this._internalTexturesCache.push(texture);
  13123. var onerror = function (message, exception) {
  13124. if (scene) {
  13125. scene._removePendingData(texture);
  13126. }
  13127. if (onLoadObserver) {
  13128. texture.onLoadedObservable.remove(onLoadObserver);
  13129. }
  13130. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  13131. if (isKTX) {
  13132. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13133. }
  13134. else if (BABYLON.Tools.UseFallbackTexture) {
  13135. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13136. }
  13137. if (onError) {
  13138. onError(message || "Unknown error", exception);
  13139. }
  13140. };
  13141. var callback = null;
  13142. // processing for non-image formats
  13143. if (isKTX || isTGA || isDDS) {
  13144. if (isKTX) {
  13145. callback = function (data) {
  13146. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  13147. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  13148. ktx.uploadLevels(_this._gl, !noMipmap);
  13149. return false;
  13150. }, samplingMode);
  13151. };
  13152. }
  13153. else if (isTGA) {
  13154. callback = function (arrayBuffer) {
  13155. var data = new Uint8Array(arrayBuffer);
  13156. var header = BABYLON.TGATools.GetTGAHeader(data);
  13157. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  13158. BABYLON.TGATools.UploadContent(_this._gl, data);
  13159. return false;
  13160. }, samplingMode);
  13161. };
  13162. }
  13163. else if (isDDS) {
  13164. callback = function (data) {
  13165. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13166. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  13167. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  13168. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  13169. return false;
  13170. }, samplingMode);
  13171. };
  13172. }
  13173. if (!buffer) {
  13174. this._loadFile(url, function (data) {
  13175. if (callback) {
  13176. callback(data);
  13177. }
  13178. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  13179. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  13180. });
  13181. }
  13182. else {
  13183. if (callback) {
  13184. callback(buffer);
  13185. }
  13186. }
  13187. // image format processing
  13188. }
  13189. else {
  13190. var onload = function (img) {
  13191. if (fromBlob && !_this._doNotHandleContextLost) {
  13192. // We need to store the image if we need to rebuild the texture
  13193. // in case of a webgl context lost
  13194. texture._buffer = img;
  13195. }
  13196. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  13197. var gl = _this._gl;
  13198. var isPot = (img.width === potWidth && img.height === potHeight);
  13199. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  13200. if (isPot) {
  13201. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13202. return false;
  13203. }
  13204. // Using shaders to rescale because canvas.drawImage is lossy
  13205. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13206. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  13207. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13208. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13209. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13210. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13211. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13212. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  13213. _this._releaseTexture(source);
  13214. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13215. continuationCallback();
  13216. });
  13217. return true;
  13218. }, samplingMode);
  13219. };
  13220. if (!fromData || isBase64)
  13221. if (buffer instanceof HTMLImageElement) {
  13222. onload(buffer);
  13223. }
  13224. else {
  13225. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13226. }
  13227. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  13228. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13229. else
  13230. onload(buffer);
  13231. }
  13232. return texture;
  13233. };
  13234. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13235. var _this = this;
  13236. var rtt = this.createRenderTargetTexture({
  13237. width: destination.width,
  13238. height: destination.height,
  13239. }, {
  13240. generateMipMaps: false,
  13241. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13242. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13243. generateDepthBuffer: false,
  13244. generateStencilBuffer: false
  13245. });
  13246. if (!this._rescalePostProcess) {
  13247. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13248. }
  13249. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13250. _this._rescalePostProcess.onApply = function (effect) {
  13251. effect._bindTexture("textureSampler", source);
  13252. };
  13253. var hostingScene = scene;
  13254. if (!hostingScene) {
  13255. hostingScene = _this.scenes[_this.scenes.length - 1];
  13256. }
  13257. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13258. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13259. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13260. _this.unBindFramebuffer(rtt);
  13261. _this._releaseTexture(rtt);
  13262. if (onComplete) {
  13263. onComplete();
  13264. }
  13265. });
  13266. };
  13267. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13268. if (compression === void 0) { compression = null; }
  13269. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13270. if (!texture) {
  13271. return;
  13272. }
  13273. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13274. var internalFormat = this._getInternalFormat(format);
  13275. var textureType = this._getWebGLTextureType(type);
  13276. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13277. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13278. if (!this._doNotHandleContextLost) {
  13279. texture._bufferView = data;
  13280. texture.format = format;
  13281. texture.type = type;
  13282. texture.invertY = invertY;
  13283. texture._compression = compression;
  13284. }
  13285. if (texture.width % 4 !== 0) {
  13286. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13287. }
  13288. if (compression && data) {
  13289. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13290. }
  13291. else {
  13292. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13293. }
  13294. if (texture.generateMipMaps) {
  13295. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13296. }
  13297. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13298. // this.resetTextureCache();
  13299. texture.isReady = true;
  13300. };
  13301. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13302. if (compression === void 0) { compression = null; }
  13303. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13304. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13305. texture.baseWidth = width;
  13306. texture.baseHeight = height;
  13307. texture.width = width;
  13308. texture.height = height;
  13309. texture.format = format;
  13310. texture.generateMipMaps = generateMipMaps;
  13311. texture.samplingMode = samplingMode;
  13312. texture.invertY = invertY;
  13313. texture._compression = compression;
  13314. texture.type = type;
  13315. if (!this._doNotHandleContextLost) {
  13316. texture._bufferView = data;
  13317. }
  13318. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13319. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13320. // Filters
  13321. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13322. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13323. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13324. if (generateMipMaps) {
  13325. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13326. }
  13327. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13328. this._internalTexturesCache.push(texture);
  13329. return texture;
  13330. };
  13331. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13332. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13333. texture.baseWidth = width;
  13334. texture.baseHeight = height;
  13335. if (generateMipMaps) {
  13336. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13337. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13338. }
  13339. // this.resetTextureCache();
  13340. texture.width = width;
  13341. texture.height = height;
  13342. texture.isReady = false;
  13343. texture.generateMipMaps = generateMipMaps;
  13344. texture.samplingMode = samplingMode;
  13345. this.updateTextureSamplingMode(samplingMode, texture);
  13346. this._internalTexturesCache.push(texture);
  13347. return texture;
  13348. };
  13349. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13350. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13351. if (texture.isCube) {
  13352. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13353. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13354. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13355. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13356. }
  13357. else if (texture.is3D) {
  13358. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13359. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13360. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13361. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13362. }
  13363. else {
  13364. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13365. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13366. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13367. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13368. }
  13369. texture.samplingMode = samplingMode;
  13370. };
  13371. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13372. if (premulAlpha === void 0) { premulAlpha = false; }
  13373. if (!texture) {
  13374. return;
  13375. }
  13376. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13377. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13378. if (premulAlpha) {
  13379. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13380. }
  13381. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13382. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13383. if (texture.generateMipMaps) {
  13384. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13385. }
  13386. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13387. if (premulAlpha) {
  13388. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13389. }
  13390. texture.isReady = true;
  13391. };
  13392. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13393. if (!texture || texture._isDisabled) {
  13394. return;
  13395. }
  13396. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13397. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13398. try {
  13399. // Testing video texture support
  13400. if (this._videoTextureSupported === undefined) {
  13401. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13402. if (this._gl.getError() !== 0) {
  13403. this._videoTextureSupported = false;
  13404. }
  13405. else {
  13406. this._videoTextureSupported = true;
  13407. }
  13408. }
  13409. // Copy video through the current working canvas if video texture is not supported
  13410. if (!this._videoTextureSupported) {
  13411. if (!texture._workingCanvas) {
  13412. texture._workingCanvas = document.createElement("canvas");
  13413. var context = texture._workingCanvas.getContext("2d");
  13414. if (!context) {
  13415. throw new Error("Unable to get 2d context");
  13416. }
  13417. texture._workingContext = context;
  13418. texture._workingCanvas.width = texture.width;
  13419. texture._workingCanvas.height = texture.height;
  13420. }
  13421. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13422. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13423. }
  13424. else {
  13425. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13426. }
  13427. if (texture.generateMipMaps) {
  13428. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13429. }
  13430. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13431. // this.resetTextureCache();
  13432. texture.isReady = true;
  13433. }
  13434. catch (ex) {
  13435. // Something unexpected
  13436. // Let's disable the texture
  13437. texture._isDisabled = true;
  13438. }
  13439. };
  13440. /**
  13441. * Updates a depth texture Comparison Mode and Function.
  13442. * If the comparison Function is equal to 0, the mode will be set to none.
  13443. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13444. * @param texture The texture to set the comparison function for
  13445. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13446. */
  13447. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13448. if (this.webGLVersion === 1) {
  13449. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13450. return;
  13451. }
  13452. var gl = this._gl;
  13453. if (texture.isCube) {
  13454. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13455. if (comparisonFunction === 0) {
  13456. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13457. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13458. }
  13459. else {
  13460. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13461. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13462. }
  13463. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13464. }
  13465. else {
  13466. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13467. if (comparisonFunction === 0) {
  13468. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13469. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13470. }
  13471. else {
  13472. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13473. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13474. }
  13475. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13476. }
  13477. texture._comparisonFunction = comparisonFunction;
  13478. };
  13479. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13480. var width = size.width || size;
  13481. var height = size.height || size;
  13482. internalTexture.baseWidth = width;
  13483. internalTexture.baseHeight = height;
  13484. internalTexture.width = width;
  13485. internalTexture.height = height;
  13486. internalTexture.isReady = true;
  13487. internalTexture.samples = 1;
  13488. internalTexture.generateMipMaps = false;
  13489. internalTexture._generateDepthBuffer = true;
  13490. internalTexture._generateStencilBuffer = generateStencil;
  13491. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13492. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13493. internalTexture._comparisonFunction = comparisonFunction;
  13494. var gl = this._gl;
  13495. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13496. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13497. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13498. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13499. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13500. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13501. if (comparisonFunction === 0) {
  13502. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13503. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13504. }
  13505. else {
  13506. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13507. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13508. }
  13509. };
  13510. /**
  13511. * Creates a depth stencil texture.
  13512. * This is only available in WebGL 2 or with the depth texture extension available.
  13513. * @param size The size of face edge in the texture.
  13514. * @param options The options defining the texture.
  13515. * @returns The texture
  13516. */
  13517. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13518. if (options.isCube) {
  13519. var width = size.width || size;
  13520. return this._createDepthStencilCubeTexture(width, options);
  13521. }
  13522. else {
  13523. return this._createDepthStencilTexture(size, options);
  13524. }
  13525. };
  13526. /**
  13527. * Creates a depth stencil texture.
  13528. * This is only available in WebGL 2 or with the depth texture extension available.
  13529. * @param size The size of face edge in the texture.
  13530. * @param options The options defining the texture.
  13531. * @returns The texture
  13532. */
  13533. Engine.prototype._createDepthStencilTexture = function (size, options) {
  13534. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13535. if (!this._caps.depthTextureExtension) {
  13536. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13537. return internalTexture;
  13538. }
  13539. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13540. var gl = this._gl;
  13541. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13542. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13543. if (this.webGLVersion > 1) {
  13544. if (internalOptions.generateStencil) {
  13545. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13546. }
  13547. else {
  13548. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13549. }
  13550. }
  13551. else {
  13552. if (internalOptions.generateStencil) {
  13553. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13554. }
  13555. else {
  13556. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13557. }
  13558. }
  13559. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13560. return internalTexture;
  13561. };
  13562. /**
  13563. * Creates a depth stencil cube texture.
  13564. * This is only available in WebGL 2.
  13565. * @param size The size of face edge in the cube texture.
  13566. * @param options The options defining the cube texture.
  13567. * @returns The cube texture
  13568. */
  13569. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  13570. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13571. internalTexture.isCube = true;
  13572. if (this.webGLVersion === 1) {
  13573. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13574. return internalTexture;
  13575. }
  13576. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13577. var gl = this._gl;
  13578. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13579. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13580. // Create the depth/stencil buffer
  13581. for (var face = 0; face < 6; face++) {
  13582. if (internalOptions.generateStencil) {
  13583. 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);
  13584. }
  13585. else {
  13586. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13587. }
  13588. }
  13589. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13590. return internalTexture;
  13591. };
  13592. /**
  13593. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13594. * @param renderTarget The render target to set the frame buffer for
  13595. */
  13596. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13597. // Create the framebuffer
  13598. var internalTexture = renderTarget.getInternalTexture();
  13599. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13600. return;
  13601. }
  13602. var gl = this._gl;
  13603. var depthStencilTexture = renderTarget.depthStencilTexture;
  13604. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13605. if (depthStencilTexture.isCube) {
  13606. if (depthStencilTexture._generateStencilBuffer) {
  13607. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13608. }
  13609. else {
  13610. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13611. }
  13612. }
  13613. else {
  13614. if (depthStencilTexture._generateStencilBuffer) {
  13615. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13616. }
  13617. else {
  13618. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13619. }
  13620. }
  13621. this.bindUnboundFramebuffer(null);
  13622. };
  13623. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13624. var fullOptions = new RenderTargetCreationOptions();
  13625. if (options !== undefined && typeof options === "object") {
  13626. fullOptions.generateMipMaps = options.generateMipMaps;
  13627. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13628. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13629. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13630. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13631. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  13632. }
  13633. else {
  13634. fullOptions.generateMipMaps = options;
  13635. fullOptions.generateDepthBuffer = true;
  13636. fullOptions.generateStencilBuffer = false;
  13637. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13638. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13639. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  13640. }
  13641. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13642. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13643. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13644. }
  13645. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13646. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13647. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13648. }
  13649. var gl = this._gl;
  13650. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13651. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13652. var width = size.width || size;
  13653. var height = size.height || size;
  13654. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13655. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13656. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13657. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13658. }
  13659. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13660. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13661. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13662. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13663. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  13664. // Create the framebuffer
  13665. var framebuffer = gl.createFramebuffer();
  13666. this.bindUnboundFramebuffer(framebuffer);
  13667. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13668. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13669. if (fullOptions.generateMipMaps) {
  13670. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13671. }
  13672. // Unbind
  13673. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13674. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13675. this.bindUnboundFramebuffer(null);
  13676. texture._framebuffer = framebuffer;
  13677. texture.baseWidth = width;
  13678. texture.baseHeight = height;
  13679. texture.width = width;
  13680. texture.height = height;
  13681. texture.isReady = true;
  13682. texture.samples = 1;
  13683. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13684. texture.samplingMode = fullOptions.samplingMode;
  13685. texture.type = fullOptions.type;
  13686. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13687. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13688. // this.resetTextureCache();
  13689. this._internalTexturesCache.push(texture);
  13690. return texture;
  13691. };
  13692. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13693. var generateMipMaps = false;
  13694. var generateDepthBuffer = true;
  13695. var generateStencilBuffer = false;
  13696. var generateDepthTexture = false;
  13697. var textureCount = 1;
  13698. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13699. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13700. var types = [], samplingModes = [];
  13701. if (options !== undefined) {
  13702. generateMipMaps = options.generateMipMaps;
  13703. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13704. generateStencilBuffer = options.generateStencilBuffer;
  13705. generateDepthTexture = options.generateDepthTexture;
  13706. textureCount = options.textureCount || 1;
  13707. if (options.types) {
  13708. types = options.types;
  13709. }
  13710. if (options.samplingModes) {
  13711. samplingModes = options.samplingModes;
  13712. }
  13713. }
  13714. var gl = this._gl;
  13715. // Create the framebuffer
  13716. var framebuffer = gl.createFramebuffer();
  13717. this.bindUnboundFramebuffer(framebuffer);
  13718. var width = size.width || size;
  13719. var height = size.height || size;
  13720. var textures = [];
  13721. var attachments = [];
  13722. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13723. for (var i = 0; i < textureCount; i++) {
  13724. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13725. var type = types[i] || defaultType;
  13726. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13727. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13728. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13729. }
  13730. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13731. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13732. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13733. }
  13734. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13735. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13736. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13737. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13738. }
  13739. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13740. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13741. textures.push(texture);
  13742. attachments.push(attachment);
  13743. gl.activeTexture(gl["TEXTURE" + i]);
  13744. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13745. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13746. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13747. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13748. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13749. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13750. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13751. if (generateMipMaps) {
  13752. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13753. }
  13754. // Unbind
  13755. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13756. texture._framebuffer = framebuffer;
  13757. texture._depthStencilBuffer = depthStencilBuffer;
  13758. texture.baseWidth = width;
  13759. texture.baseHeight = height;
  13760. texture.width = width;
  13761. texture.height = height;
  13762. texture.isReady = true;
  13763. texture.samples = 1;
  13764. texture.generateMipMaps = generateMipMaps;
  13765. texture.samplingMode = samplingMode;
  13766. texture.type = type;
  13767. texture._generateDepthBuffer = generateDepthBuffer;
  13768. texture._generateStencilBuffer = generateStencilBuffer;
  13769. texture._attachments = attachments;
  13770. this._internalTexturesCache.push(texture);
  13771. }
  13772. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13773. // Depth texture
  13774. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13775. gl.activeTexture(gl.TEXTURE0);
  13776. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13777. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13778. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13779. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13780. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13781. 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);
  13782. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13783. depthTexture._framebuffer = framebuffer;
  13784. depthTexture.baseWidth = width;
  13785. depthTexture.baseHeight = height;
  13786. depthTexture.width = width;
  13787. depthTexture.height = height;
  13788. depthTexture.isReady = true;
  13789. depthTexture.samples = 1;
  13790. depthTexture.generateMipMaps = generateMipMaps;
  13791. depthTexture.samplingMode = gl.NEAREST;
  13792. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13793. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13794. textures.push(depthTexture);
  13795. this._internalTexturesCache.push(depthTexture);
  13796. }
  13797. gl.drawBuffers(attachments);
  13798. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13799. this.bindUnboundFramebuffer(null);
  13800. this.resetTextureCache();
  13801. return textures;
  13802. };
  13803. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13804. if (samples === void 0) { samples = 1; }
  13805. var depthStencilBuffer = null;
  13806. var gl = this._gl;
  13807. // Create the depth/stencil buffer
  13808. if (generateStencilBuffer) {
  13809. depthStencilBuffer = gl.createRenderbuffer();
  13810. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13811. if (samples > 1) {
  13812. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13813. }
  13814. else {
  13815. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13816. }
  13817. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13818. }
  13819. else if (generateDepthBuffer) {
  13820. depthStencilBuffer = gl.createRenderbuffer();
  13821. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13822. if (samples > 1) {
  13823. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13824. }
  13825. else {
  13826. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13827. }
  13828. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13829. }
  13830. return depthStencilBuffer;
  13831. };
  13832. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13833. if (this.webGLVersion < 2 || !texture) {
  13834. return 1;
  13835. }
  13836. if (texture.samples === samples) {
  13837. return samples;
  13838. }
  13839. var gl = this._gl;
  13840. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13841. // Dispose previous render buffers
  13842. if (texture._depthStencilBuffer) {
  13843. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13844. texture._depthStencilBuffer = null;
  13845. }
  13846. if (texture._MSAAFramebuffer) {
  13847. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13848. texture._MSAAFramebuffer = null;
  13849. }
  13850. if (texture._MSAARenderBuffer) {
  13851. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13852. texture._MSAARenderBuffer = null;
  13853. }
  13854. if (samples > 1) {
  13855. var framebuffer = gl.createFramebuffer();
  13856. if (!framebuffer) {
  13857. throw new Error("Unable to create multi sampled framebuffer");
  13858. }
  13859. texture._MSAAFramebuffer = framebuffer;
  13860. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13861. var colorRenderbuffer = gl.createRenderbuffer();
  13862. if (!colorRenderbuffer) {
  13863. throw new Error("Unable to create multi sampled framebuffer");
  13864. }
  13865. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13866. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13867. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13868. texture._MSAARenderBuffer = colorRenderbuffer;
  13869. }
  13870. else {
  13871. this.bindUnboundFramebuffer(texture._framebuffer);
  13872. }
  13873. texture.samples = samples;
  13874. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13875. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13876. this.bindUnboundFramebuffer(null);
  13877. return samples;
  13878. };
  13879. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13880. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13881. return 1;
  13882. }
  13883. if (textures[0].samples === samples) {
  13884. return samples;
  13885. }
  13886. var gl = this._gl;
  13887. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13888. // Dispose previous render buffers
  13889. if (textures[0]._depthStencilBuffer) {
  13890. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13891. textures[0]._depthStencilBuffer = null;
  13892. }
  13893. if (textures[0]._MSAAFramebuffer) {
  13894. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13895. textures[0]._MSAAFramebuffer = null;
  13896. }
  13897. for (var i = 0; i < textures.length; i++) {
  13898. if (textures[i]._MSAARenderBuffer) {
  13899. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13900. textures[i]._MSAARenderBuffer = null;
  13901. }
  13902. }
  13903. if (samples > 1) {
  13904. var framebuffer = gl.createFramebuffer();
  13905. if (!framebuffer) {
  13906. throw new Error("Unable to create multi sampled framebuffer");
  13907. }
  13908. this.bindUnboundFramebuffer(framebuffer);
  13909. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13910. var attachments = [];
  13911. for (var i = 0; i < textures.length; i++) {
  13912. var texture = textures[i];
  13913. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13914. var colorRenderbuffer = gl.createRenderbuffer();
  13915. if (!colorRenderbuffer) {
  13916. throw new Error("Unable to create multi sampled framebuffer");
  13917. }
  13918. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13919. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13920. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13921. texture._MSAAFramebuffer = framebuffer;
  13922. texture._MSAARenderBuffer = colorRenderbuffer;
  13923. texture.samples = samples;
  13924. texture._depthStencilBuffer = depthStencilBuffer;
  13925. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13926. attachments.push(attachment);
  13927. }
  13928. gl.drawBuffers(attachments);
  13929. }
  13930. else {
  13931. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13932. }
  13933. this.bindUnboundFramebuffer(null);
  13934. return samples;
  13935. };
  13936. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13937. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13938. };
  13939. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13940. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13941. };
  13942. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13943. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  13944. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13945. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13946. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13947. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13948. }
  13949. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13950. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13951. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13952. }
  13953. var gl = this._gl;
  13954. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13955. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13956. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13957. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13958. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13959. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13960. }
  13961. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13962. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13963. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13964. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13965. for (var face = 0; face < 6; face++) {
  13966. 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);
  13967. }
  13968. // Create the framebuffer
  13969. var framebuffer = gl.createFramebuffer();
  13970. this.bindUnboundFramebuffer(framebuffer);
  13971. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  13972. // MipMaps
  13973. if (fullOptions.generateMipMaps) {
  13974. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13975. }
  13976. // Unbind
  13977. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13978. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13979. this.bindUnboundFramebuffer(null);
  13980. texture._framebuffer = framebuffer;
  13981. texture.width = size;
  13982. texture.height = size;
  13983. texture.isReady = true;
  13984. texture.isCube = true;
  13985. texture.samples = 1;
  13986. texture.generateMipMaps = fullOptions.generateMipMaps;
  13987. texture.samplingMode = fullOptions.samplingMode;
  13988. texture.type = fullOptions.type;
  13989. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13990. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  13991. this._internalTexturesCache.push(texture);
  13992. return texture;
  13993. };
  13994. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13995. var _this = this;
  13996. if (onLoad === void 0) { onLoad = null; }
  13997. if (onError === void 0) { onError = null; }
  13998. if (forcedExtension === void 0) { forcedExtension = null; }
  13999. var callback = function (loadData) {
  14000. if (!loadData) {
  14001. if (onLoad) {
  14002. onLoad(null);
  14003. }
  14004. return;
  14005. }
  14006. var texture = loadData.texture;
  14007. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  14008. texture._lodGenerationScale = scale;
  14009. texture._lodGenerationOffset = offset;
  14010. if (_this._caps.textureLOD) {
  14011. // Do not add extra process if texture lod is supported.
  14012. if (onLoad) {
  14013. onLoad(texture);
  14014. }
  14015. return;
  14016. }
  14017. var mipSlices = 3;
  14018. var gl = _this._gl;
  14019. var width = loadData.width;
  14020. if (!width) {
  14021. return;
  14022. }
  14023. var textures = [];
  14024. for (var i = 0; i < mipSlices; i++) {
  14025. //compute LOD from even spacing in smoothness (matching shader calculation)
  14026. var smoothness = i / (mipSlices - 1);
  14027. var roughness = 1 - smoothness;
  14028. var minLODIndex = offset; // roughness = 0
  14029. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  14030. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  14031. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  14032. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14033. glTextureFromLod.isCube = true;
  14034. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  14035. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14036. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14037. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14038. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14039. if (loadData.isDDS) {
  14040. var info = loadData.info;
  14041. var data = loadData.data;
  14042. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14043. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  14044. }
  14045. else {
  14046. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  14047. }
  14048. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14049. // Wrap in a base texture for easy binding.
  14050. var lodTexture = new BABYLON.BaseTexture(scene);
  14051. lodTexture.isCube = true;
  14052. lodTexture._texture = glTextureFromLod;
  14053. glTextureFromLod.isReady = true;
  14054. textures.push(lodTexture);
  14055. }
  14056. texture._lodTextureHigh = textures[2];
  14057. texture._lodTextureMid = textures[1];
  14058. texture._lodTextureLow = textures[0];
  14059. if (onLoad) {
  14060. onLoad(texture);
  14061. }
  14062. };
  14063. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  14064. };
  14065. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  14066. var _this = this;
  14067. if (onLoad === void 0) { onLoad = null; }
  14068. if (onError === void 0) { onError = null; }
  14069. if (forcedExtension === void 0) { forcedExtension = null; }
  14070. var gl = this._gl;
  14071. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  14072. texture.isCube = true;
  14073. texture.url = rootUrl;
  14074. texture.generateMipMaps = !noMipmap;
  14075. if (!this._doNotHandleContextLost) {
  14076. texture._extension = forcedExtension;
  14077. texture._files = files;
  14078. }
  14079. var isKTX = false;
  14080. var isDDS = false;
  14081. var lastDot = rootUrl.lastIndexOf('.');
  14082. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  14083. if (this._textureFormatInUse) {
  14084. extension = this._textureFormatInUse;
  14085. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  14086. isKTX = true;
  14087. }
  14088. else {
  14089. isDDS = (extension === ".dds");
  14090. }
  14091. var onerror = function (request, exception) {
  14092. if (onError && request) {
  14093. onError(request.status + " " + request.statusText, exception);
  14094. }
  14095. };
  14096. if (isKTX) {
  14097. this._loadFile(rootUrl, function (data) {
  14098. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  14099. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  14100. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14101. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  14102. ktx.uploadLevels(_this._gl, !noMipmap);
  14103. _this.setCubeMapTextureParams(gl, loadMipmap);
  14104. texture.width = ktx.pixelWidth;
  14105. texture.height = ktx.pixelHeight;
  14106. texture.isReady = true;
  14107. }, undefined, undefined, true, onerror);
  14108. }
  14109. else if (isDDS) {
  14110. if (files && files.length === 6) {
  14111. this._cascadeLoadFiles(scene, function (imgs) {
  14112. var info;
  14113. var loadMipmap = false;
  14114. var width = 0;
  14115. for (var index = 0; index < imgs.length; index++) {
  14116. var data = imgs[index];
  14117. info = BABYLON.DDSTools.GetDDSInfo(data);
  14118. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14119. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14120. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14121. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  14122. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14123. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14124. }
  14125. texture.width = info.width;
  14126. texture.height = info.height;
  14127. texture.type = info.textureType;
  14128. width = info.width;
  14129. }
  14130. _this.setCubeMapTextureParams(gl, loadMipmap);
  14131. texture.isReady = true;
  14132. if (onLoad) {
  14133. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  14134. }
  14135. }, files, onError);
  14136. }
  14137. else {
  14138. this._loadFile(rootUrl, function (data) {
  14139. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14140. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14141. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14142. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14143. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  14144. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14145. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14146. }
  14147. _this.setCubeMapTextureParams(gl, loadMipmap);
  14148. texture.width = info.width;
  14149. texture.height = info.height;
  14150. texture.isReady = true;
  14151. texture.type = info.textureType;
  14152. if (onLoad) {
  14153. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  14154. }
  14155. }, undefined, undefined, true, onerror);
  14156. }
  14157. }
  14158. else {
  14159. if (!files) {
  14160. throw new Error("Cannot load cubemap because files were not defined");
  14161. }
  14162. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  14163. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  14164. var height = width;
  14165. _this._prepareWorkingCanvas();
  14166. if (!_this._workingCanvas || !_this._workingContext) {
  14167. return;
  14168. }
  14169. _this._workingCanvas.width = width;
  14170. _this._workingCanvas.height = height;
  14171. var faces = [
  14172. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  14173. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  14174. ];
  14175. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14176. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14177. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  14178. for (var index = 0; index < faces.length; index++) {
  14179. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  14180. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14181. }
  14182. if (!noMipmap) {
  14183. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14184. }
  14185. _this.setCubeMapTextureParams(gl, !noMipmap);
  14186. texture.width = width;
  14187. texture.height = height;
  14188. texture.isReady = true;
  14189. if (format) {
  14190. texture.format = format;
  14191. }
  14192. texture.onLoadedObservable.notifyObservers(texture);
  14193. texture.onLoadedObservable.clear();
  14194. if (onLoad) {
  14195. onLoad();
  14196. }
  14197. }, files, onError);
  14198. }
  14199. this._internalTexturesCache.push(texture);
  14200. return texture;
  14201. };
  14202. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  14203. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14204. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  14205. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14206. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14207. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14208. // this.resetTextureCache();
  14209. };
  14210. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  14211. if (compression === void 0) { compression = null; }
  14212. if (level === void 0) { level = 0; }
  14213. texture._bufferViewArray = data;
  14214. texture.format = format;
  14215. texture.type = type;
  14216. texture.invertY = invertY;
  14217. texture._compression = compression;
  14218. var gl = this._gl;
  14219. var textureType = this._getWebGLTextureType(type);
  14220. var internalFormat = this._getInternalFormat(format);
  14221. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  14222. var needConversion = false;
  14223. if (internalFormat === gl.RGB) {
  14224. internalFormat = gl.RGBA;
  14225. needConversion = true;
  14226. }
  14227. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14228. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14229. if (texture.width % 4 !== 0) {
  14230. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14231. }
  14232. // Data are known to be in +X +Y +Z -X -Y -Z
  14233. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14234. var faceData = data[faceIndex];
  14235. if (compression) {
  14236. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14237. }
  14238. else {
  14239. if (needConversion) {
  14240. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14241. }
  14242. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14243. }
  14244. }
  14245. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14246. if (isPot && texture.generateMipMaps && level === 0) {
  14247. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14248. }
  14249. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14250. // this.resetTextureCache();
  14251. texture.isReady = true;
  14252. };
  14253. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14254. if (compression === void 0) { compression = null; }
  14255. var gl = this._gl;
  14256. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14257. texture.isCube = true;
  14258. texture.generateMipMaps = generateMipMaps;
  14259. texture.format = format;
  14260. texture.type = type;
  14261. if (!this._doNotHandleContextLost) {
  14262. texture._bufferViewArray = data;
  14263. }
  14264. var textureType = this._getWebGLTextureType(type);
  14265. var internalFormat = this._getInternalFormat(format);
  14266. if (internalFormat === gl.RGB) {
  14267. internalFormat = gl.RGBA;
  14268. }
  14269. var width = size;
  14270. var height = width;
  14271. texture.width = width;
  14272. texture.height = height;
  14273. // Double check on POT to generate Mips.
  14274. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14275. if (!isPot) {
  14276. generateMipMaps = false;
  14277. }
  14278. // Upload data if needed. The texture won't be ready until then.
  14279. if (data) {
  14280. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14281. }
  14282. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14283. // Filters
  14284. if (data && generateMipMaps) {
  14285. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14286. }
  14287. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14288. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14289. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14290. }
  14291. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14292. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14293. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14294. }
  14295. else {
  14296. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14297. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14298. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14299. }
  14300. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14301. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14302. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14303. return texture;
  14304. };
  14305. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14306. var _this = this;
  14307. if (onLoad === void 0) { onLoad = null; }
  14308. if (onError === void 0) { onError = null; }
  14309. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14310. if (invertY === void 0) { invertY = false; }
  14311. var gl = this._gl;
  14312. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14313. scene._addPendingData(texture);
  14314. texture.url = url;
  14315. this._internalTexturesCache.push(texture);
  14316. var onerror = function (request, exception) {
  14317. scene._removePendingData(texture);
  14318. if (onError && request) {
  14319. onError(request.status + " " + request.statusText, exception);
  14320. }
  14321. };
  14322. var internalCallback = function (data) {
  14323. var width = texture.width;
  14324. var faceDataArrays = callback(data);
  14325. if (!faceDataArrays) {
  14326. return;
  14327. }
  14328. if (mipmmapGenerator) {
  14329. var textureType = _this._getWebGLTextureType(type);
  14330. var internalFormat = _this._getInternalFormat(format);
  14331. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14332. var needConversion = false;
  14333. if (internalFormat === gl.RGB) {
  14334. internalFormat = gl.RGBA;
  14335. needConversion = true;
  14336. }
  14337. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14338. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14339. var mipData = mipmmapGenerator(faceDataArrays);
  14340. for (var level = 0; level < mipData.length; level++) {
  14341. var mipSize = width >> level;
  14342. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14343. var mipFaceData = mipData[level][faceIndex];
  14344. if (needConversion) {
  14345. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14346. }
  14347. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14348. }
  14349. }
  14350. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14351. }
  14352. else {
  14353. texture.generateMipMaps = !noMipmap;
  14354. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14355. }
  14356. texture.isReady = true;
  14357. // this.resetTextureCache();
  14358. scene._removePendingData(texture);
  14359. if (onLoad) {
  14360. onLoad();
  14361. }
  14362. };
  14363. this._loadFile(url, function (data) {
  14364. internalCallback(data);
  14365. }, undefined, scene.database, true, onerror);
  14366. return texture;
  14367. };
  14368. ;
  14369. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14370. if (compression === void 0) { compression = null; }
  14371. var internalFormat = this._getInternalFormat(format);
  14372. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14373. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14374. if (!this._doNotHandleContextLost) {
  14375. texture._bufferView = data;
  14376. texture.format = format;
  14377. texture.invertY = invertY;
  14378. texture._compression = compression;
  14379. }
  14380. if (texture.width % 4 !== 0) {
  14381. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14382. }
  14383. if (compression && data) {
  14384. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14385. }
  14386. else {
  14387. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14388. }
  14389. if (texture.generateMipMaps) {
  14390. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14391. }
  14392. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14393. // this.resetTextureCache();
  14394. texture.isReady = true;
  14395. };
  14396. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14397. if (compression === void 0) { compression = null; }
  14398. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14399. texture.baseWidth = width;
  14400. texture.baseHeight = height;
  14401. texture.baseDepth = depth;
  14402. texture.width = width;
  14403. texture.height = height;
  14404. texture.depth = depth;
  14405. texture.format = format;
  14406. texture.generateMipMaps = generateMipMaps;
  14407. texture.samplingMode = samplingMode;
  14408. texture.is3D = true;
  14409. if (!this._doNotHandleContextLost) {
  14410. texture._bufferView = data;
  14411. }
  14412. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14413. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14414. // Filters
  14415. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14416. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14417. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14418. if (generateMipMaps) {
  14419. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14420. }
  14421. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14422. this._internalTexturesCache.push(texture);
  14423. return texture;
  14424. };
  14425. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14426. var gl = this._gl;
  14427. if (!gl) {
  14428. return;
  14429. }
  14430. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14431. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14432. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14433. if (!noMipmap && !isCompressed) {
  14434. gl.generateMipmap(gl.TEXTURE_2D);
  14435. }
  14436. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14437. // this.resetTextureCache();
  14438. if (scene) {
  14439. scene._removePendingData(texture);
  14440. }
  14441. texture.onLoadedObservable.notifyObservers(texture);
  14442. texture.onLoadedObservable.clear();
  14443. };
  14444. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14445. var _this = this;
  14446. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14447. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14448. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14449. var gl = this._gl;
  14450. if (!gl) {
  14451. return;
  14452. }
  14453. if (!texture._webGLTexture) {
  14454. // this.resetTextureCache();
  14455. if (scene) {
  14456. scene._removePendingData(texture);
  14457. }
  14458. return;
  14459. }
  14460. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14461. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14462. texture.baseWidth = width;
  14463. texture.baseHeight = height;
  14464. texture.width = potWidth;
  14465. texture.height = potHeight;
  14466. texture.isReady = true;
  14467. if (processFunction(potWidth, potHeight, function () {
  14468. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14469. })) {
  14470. // Returning as texture needs extra async steps
  14471. return;
  14472. }
  14473. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14474. };
  14475. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14476. // Create new RGBA data container.
  14477. var rgbaData;
  14478. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14479. rgbaData = new Float32Array(width * height * 4);
  14480. }
  14481. else {
  14482. rgbaData = new Uint32Array(width * height * 4);
  14483. }
  14484. // Convert each pixel.
  14485. for (var x = 0; x < width; x++) {
  14486. for (var y = 0; y < height; y++) {
  14487. var index = (y * width + x) * 3;
  14488. var newIndex = (y * width + x) * 4;
  14489. // Map Old Value to new value.
  14490. rgbaData[newIndex + 0] = rgbData[index + 0];
  14491. rgbaData[newIndex + 1] = rgbData[index + 1];
  14492. rgbaData[newIndex + 2] = rgbData[index + 2];
  14493. // Add fully opaque alpha channel.
  14494. rgbaData[newIndex + 3] = 1;
  14495. }
  14496. }
  14497. return rgbaData;
  14498. };
  14499. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14500. var gl = this._gl;
  14501. if (texture._framebuffer) {
  14502. gl.deleteFramebuffer(texture._framebuffer);
  14503. texture._framebuffer = null;
  14504. }
  14505. if (texture._depthStencilBuffer) {
  14506. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14507. texture._depthStencilBuffer = null;
  14508. }
  14509. if (texture._MSAAFramebuffer) {
  14510. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14511. texture._MSAAFramebuffer = null;
  14512. }
  14513. if (texture._MSAARenderBuffer) {
  14514. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14515. texture._MSAARenderBuffer = null;
  14516. }
  14517. };
  14518. Engine.prototype._releaseTexture = function (texture) {
  14519. var gl = this._gl;
  14520. this._releaseFramebufferObjects(texture);
  14521. gl.deleteTexture(texture._webGLTexture);
  14522. // Unbind channels
  14523. this.unbindAllTextures();
  14524. var index = this._internalTexturesCache.indexOf(texture);
  14525. if (index !== -1) {
  14526. this._internalTexturesCache.splice(index, 1);
  14527. }
  14528. // Integrated fixed lod samplers.
  14529. if (texture._lodTextureHigh) {
  14530. texture._lodTextureHigh.dispose();
  14531. }
  14532. if (texture._lodTextureMid) {
  14533. texture._lodTextureMid.dispose();
  14534. }
  14535. if (texture._lodTextureLow) {
  14536. texture._lodTextureLow.dispose();
  14537. }
  14538. };
  14539. Engine.prototype.setProgram = function (program) {
  14540. if (this._currentProgram !== program) {
  14541. this._gl.useProgram(program);
  14542. this._currentProgram = program;
  14543. }
  14544. };
  14545. Engine.prototype.bindSamplers = function (effect) {
  14546. this.setProgram(effect.getProgram());
  14547. var samplers = effect.getSamplers();
  14548. for (var index = 0; index < samplers.length; index++) {
  14549. var uniform = effect.getUniform(samplers[index]);
  14550. if (uniform) {
  14551. this._boundUniforms[index] = uniform;
  14552. }
  14553. }
  14554. this._currentEffect = null;
  14555. };
  14556. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14557. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14558. return;
  14559. }
  14560. // Remove
  14561. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14562. // Bind last to it
  14563. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14564. // Bind to dummy
  14565. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14566. };
  14567. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14568. if (!internalTexture) {
  14569. return -1;
  14570. }
  14571. internalTexture._initialSlot = channel;
  14572. if (this.disableTextureBindingOptimization) {
  14573. if (channel !== internalTexture._designatedSlot) {
  14574. this._textureCollisions.addCount(1, false);
  14575. }
  14576. }
  14577. else {
  14578. if (channel !== internalTexture._designatedSlot) {
  14579. if (internalTexture._designatedSlot > -1) {
  14580. return internalTexture._designatedSlot;
  14581. }
  14582. else {
  14583. // No slot for this texture, let's pick a new one (if we find a free slot)
  14584. if (this._nextFreeTextureSlots.length) {
  14585. return this._nextFreeTextureSlots[0];
  14586. }
  14587. // We need to recycle the oldest bound texture, sorry.
  14588. this._textureCollisions.addCount(1, false);
  14589. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14590. }
  14591. }
  14592. }
  14593. return channel;
  14594. };
  14595. Engine.prototype._linkTrackers = function (previous, next) {
  14596. previous.next = next;
  14597. next.previous = previous;
  14598. };
  14599. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14600. var currentSlot = internalTexture._designatedSlot;
  14601. if (currentSlot === -1) {
  14602. return -1;
  14603. }
  14604. internalTexture._designatedSlot = -1;
  14605. if (this.disableTextureBindingOptimization) {
  14606. return -1;
  14607. }
  14608. // Remove from bound list
  14609. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14610. // Free the slot
  14611. this._boundTexturesCache[currentSlot] = null;
  14612. this._nextFreeTextureSlots.push(currentSlot);
  14613. return currentSlot;
  14614. };
  14615. Engine.prototype._activateCurrentTexture = function () {
  14616. if (this._currentTextureChannel !== this._activeChannel) {
  14617. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14618. this._currentTextureChannel = this._activeChannel;
  14619. }
  14620. };
  14621. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14622. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14623. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14624. this._activeChannel = texture._designatedSlot;
  14625. }
  14626. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14627. var isTextureForRendering = texture && texture._initialSlot > -1;
  14628. if (currentTextureBound !== texture) {
  14629. if (currentTextureBound) {
  14630. this._removeDesignatedSlot(currentTextureBound);
  14631. }
  14632. this._activateCurrentTexture();
  14633. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14634. this._boundTexturesCache[this._activeChannel] = texture;
  14635. if (texture) {
  14636. if (!this.disableTextureBindingOptimization) {
  14637. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14638. if (slotIndex > -1) {
  14639. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14640. }
  14641. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14642. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14643. }
  14644. texture._designatedSlot = this._activeChannel;
  14645. }
  14646. }
  14647. else if (forTextureDataUpdate) {
  14648. this._activateCurrentTexture();
  14649. }
  14650. if (isTextureForRendering && !forTextureDataUpdate) {
  14651. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14652. }
  14653. };
  14654. Engine.prototype._bindTexture = function (channel, texture) {
  14655. if (channel < 0) {
  14656. return;
  14657. }
  14658. if (texture) {
  14659. channel = this._getCorrectTextureChannel(channel, texture);
  14660. }
  14661. this._activeChannel = channel;
  14662. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14663. };
  14664. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14665. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14666. };
  14667. Engine.prototype.unbindAllTextures = function () {
  14668. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14669. this._activeChannel = channel;
  14670. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14671. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14672. if (this.webGLVersion > 1) {
  14673. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14674. }
  14675. }
  14676. };
  14677. /**
  14678. * Sets a texture to the according uniform.
  14679. * @param channel The texture channel
  14680. * @param uniform The uniform to set
  14681. * @param texture The texture to apply
  14682. */
  14683. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14684. if (channel < 0) {
  14685. return;
  14686. }
  14687. if (uniform) {
  14688. this._boundUniforms[channel] = uniform;
  14689. }
  14690. this._setTexture(channel, texture);
  14691. };
  14692. /**
  14693. * Sets a depth stencil texture from a render target to the according uniform.
  14694. * @param channel The texture channel
  14695. * @param uniform The uniform to set
  14696. * @param texture The render target texture containing the depth stencil texture to apply
  14697. */
  14698. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  14699. if (channel < 0) {
  14700. return;
  14701. }
  14702. if (uniform) {
  14703. this._boundUniforms[channel] = uniform;
  14704. }
  14705. if (!texture || !texture.depthStencilTexture) {
  14706. this._setTexture(channel, null);
  14707. }
  14708. else {
  14709. this._setTexture(channel, texture, false, true);
  14710. }
  14711. };
  14712. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14713. var uniform = this._boundUniforms[sourceSlot];
  14714. if (uniform._currentState === destination) {
  14715. return;
  14716. }
  14717. this._gl.uniform1i(uniform, destination);
  14718. uniform._currentState = destination;
  14719. };
  14720. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  14721. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14722. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  14723. // Not ready?
  14724. if (!texture) {
  14725. if (this._boundTexturesCache[channel] != null) {
  14726. this._activeChannel = channel;
  14727. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14728. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14729. if (this.webGLVersion > 1) {
  14730. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14731. }
  14732. }
  14733. return false;
  14734. }
  14735. // Video
  14736. if (texture.video) {
  14737. this._activeChannel = channel;
  14738. texture.update();
  14739. }
  14740. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14741. texture.delayLoad();
  14742. return false;
  14743. }
  14744. var internalTexture;
  14745. if (depthStencilTexture) {
  14746. internalTexture = texture.depthStencilTexture;
  14747. }
  14748. else if (texture.isReady()) {
  14749. internalTexture = texture.getInternalTexture();
  14750. }
  14751. else if (texture.isCube) {
  14752. internalTexture = this.emptyCubeTexture;
  14753. }
  14754. else if (texture.is3D) {
  14755. internalTexture = this.emptyTexture3D;
  14756. }
  14757. else {
  14758. internalTexture = this.emptyTexture;
  14759. }
  14760. if (!isPartOfTextureArray) {
  14761. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14762. }
  14763. if (this._boundTexturesCache[channel] === internalTexture) {
  14764. this._moveBoundTextureOnTop(internalTexture);
  14765. if (!isPartOfTextureArray) {
  14766. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14767. }
  14768. return false;
  14769. }
  14770. this._activeChannel = channel;
  14771. if (internalTexture && internalTexture.is3D) {
  14772. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14773. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14774. internalTexture._cachedWrapU = texture.wrapU;
  14775. switch (texture.wrapU) {
  14776. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14777. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14778. break;
  14779. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14780. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14781. break;
  14782. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14783. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14784. break;
  14785. }
  14786. }
  14787. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14788. internalTexture._cachedWrapV = texture.wrapV;
  14789. switch (texture.wrapV) {
  14790. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14791. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14792. break;
  14793. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14794. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14795. break;
  14796. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14797. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14798. break;
  14799. }
  14800. }
  14801. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14802. internalTexture._cachedWrapR = texture.wrapR;
  14803. switch (texture.wrapR) {
  14804. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14805. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14806. break;
  14807. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14808. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14809. break;
  14810. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14811. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14812. break;
  14813. }
  14814. }
  14815. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14816. }
  14817. else if (internalTexture && internalTexture.isCube) {
  14818. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14819. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14820. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14821. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14822. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14823. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14824. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14825. }
  14826. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14827. }
  14828. else {
  14829. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14830. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14831. internalTexture._cachedWrapU = texture.wrapU;
  14832. switch (texture.wrapU) {
  14833. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14834. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14835. break;
  14836. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14837. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14838. break;
  14839. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14840. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14841. break;
  14842. }
  14843. }
  14844. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14845. internalTexture._cachedWrapV = texture.wrapV;
  14846. switch (texture.wrapV) {
  14847. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14848. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14849. break;
  14850. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14851. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14852. break;
  14853. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14854. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14855. break;
  14856. }
  14857. }
  14858. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14859. }
  14860. return true;
  14861. };
  14862. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14863. if (channel < 0 || !uniform) {
  14864. return;
  14865. }
  14866. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14867. this._textureUnits = new Int32Array(textures.length);
  14868. }
  14869. for (var i = 0; i < textures.length; i++) {
  14870. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14871. }
  14872. this._gl.uniform1iv(uniform, this._textureUnits);
  14873. for (var index = 0; index < textures.length; index++) {
  14874. this._setTexture(this._textureUnits[index], textures[index], true);
  14875. }
  14876. };
  14877. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14878. var internalTexture = texture.getInternalTexture();
  14879. if (!internalTexture) {
  14880. return;
  14881. }
  14882. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14883. var value = texture.anisotropicFilteringLevel;
  14884. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14885. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14886. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14887. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14888. }
  14889. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14890. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14891. internalTexture._cachedAnisotropicFilteringLevel = value;
  14892. }
  14893. };
  14894. Engine.prototype.readPixels = function (x, y, width, height) {
  14895. var data = new Uint8Array(height * width * 4);
  14896. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14897. return data;
  14898. };
  14899. /**
  14900. * Add an externaly attached data from its key.
  14901. * This method call will fail and return false, if such key already exists.
  14902. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14903. * @param key the unique key that identifies the data
  14904. * @param data the data object to associate to the key for this Engine instance
  14905. * @return true if no such key were already present and the data was added successfully, false otherwise
  14906. */
  14907. Engine.prototype.addExternalData = function (key, data) {
  14908. if (!this._externalData) {
  14909. this._externalData = new BABYLON.StringDictionary();
  14910. }
  14911. return this._externalData.add(key, data);
  14912. };
  14913. /**
  14914. * Get an externaly attached data from its key
  14915. * @param key the unique key that identifies the data
  14916. * @return the associated data, if present (can be null), or undefined if not present
  14917. */
  14918. Engine.prototype.getExternalData = function (key) {
  14919. if (!this._externalData) {
  14920. this._externalData = new BABYLON.StringDictionary();
  14921. }
  14922. return this._externalData.get(key);
  14923. };
  14924. /**
  14925. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14926. * @param key the unique key that identifies the data
  14927. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14928. * @return the associated data, can be null if the factory returned null.
  14929. */
  14930. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14931. if (!this._externalData) {
  14932. this._externalData = new BABYLON.StringDictionary();
  14933. }
  14934. return this._externalData.getOrAddWithFactory(key, factory);
  14935. };
  14936. /**
  14937. * Remove an externaly attached data from the Engine instance
  14938. * @param key the unique key that identifies the data
  14939. * @return true if the data was successfully removed, false if it doesn't exist
  14940. */
  14941. Engine.prototype.removeExternalData = function (key) {
  14942. if (!this._externalData) {
  14943. this._externalData = new BABYLON.StringDictionary();
  14944. }
  14945. return this._externalData.remove(key);
  14946. };
  14947. Engine.prototype.unbindAllAttributes = function () {
  14948. if (this._mustWipeVertexAttributes) {
  14949. this._mustWipeVertexAttributes = false;
  14950. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14951. this._gl.disableVertexAttribArray(i);
  14952. this._vertexAttribArraysEnabled[i] = false;
  14953. this._currentBufferPointers[i].active = false;
  14954. }
  14955. return;
  14956. }
  14957. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14958. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14959. continue;
  14960. }
  14961. this._gl.disableVertexAttribArray(i);
  14962. this._vertexAttribArraysEnabled[i] = false;
  14963. this._currentBufferPointers[i].active = false;
  14964. }
  14965. };
  14966. Engine.prototype.releaseEffects = function () {
  14967. for (var name in this._compiledEffects) {
  14968. this._deleteProgram(this._compiledEffects[name]._program);
  14969. }
  14970. this._compiledEffects = {};
  14971. };
  14972. // Dispose
  14973. Engine.prototype.dispose = function () {
  14974. this.hideLoadingUI();
  14975. this.stopRenderLoop();
  14976. // Release postProcesses
  14977. while (this.postProcesses.length) {
  14978. this.postProcesses[0].dispose();
  14979. }
  14980. // Empty texture
  14981. if (this._emptyTexture) {
  14982. this._releaseTexture(this._emptyTexture);
  14983. this._emptyTexture = null;
  14984. }
  14985. if (this._emptyCubeTexture) {
  14986. this._releaseTexture(this._emptyCubeTexture);
  14987. this._emptyCubeTexture = null;
  14988. }
  14989. // Rescale PP
  14990. if (this._rescalePostProcess) {
  14991. this._rescalePostProcess.dispose();
  14992. }
  14993. // Release scenes
  14994. while (this.scenes.length) {
  14995. this.scenes[0].dispose();
  14996. }
  14997. // Release audio engine
  14998. if (Engine.audioEngine) {
  14999. Engine.audioEngine.dispose();
  15000. }
  15001. // Release effects
  15002. this.releaseEffects();
  15003. // Unbind
  15004. this.unbindAllAttributes();
  15005. if (this._dummyFramebuffer) {
  15006. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  15007. }
  15008. //WebVR
  15009. this.disableVR();
  15010. // Events
  15011. if (BABYLON.Tools.IsWindowObjectExist()) {
  15012. window.removeEventListener("blur", this._onBlur);
  15013. window.removeEventListener("focus", this._onFocus);
  15014. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  15015. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  15016. if (this._renderingCanvas) {
  15017. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  15018. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  15019. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  15020. if (!this._doNotHandleContextLost) {
  15021. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  15022. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  15023. }
  15024. }
  15025. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  15026. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  15027. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  15028. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  15029. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  15030. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  15031. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  15032. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  15033. if (this._onVrDisplayConnect) {
  15034. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  15035. if (this._onVrDisplayDisconnect) {
  15036. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  15037. }
  15038. if (this._onVrDisplayPresentChange) {
  15039. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  15040. }
  15041. this._onVrDisplayConnect = null;
  15042. this._onVrDisplayDisconnect = null;
  15043. }
  15044. }
  15045. // Remove from Instances
  15046. var index = Engine.Instances.indexOf(this);
  15047. if (index >= 0) {
  15048. Engine.Instances.splice(index, 1);
  15049. }
  15050. this._workingCanvas = null;
  15051. this._workingContext = null;
  15052. this._currentBufferPointers = [];
  15053. this._renderingCanvas = null;
  15054. this._currentProgram = null;
  15055. this._bindedRenderFunction = null;
  15056. this.onResizeObservable.clear();
  15057. this.onCanvasBlurObservable.clear();
  15058. this.onCanvasFocusObservable.clear();
  15059. this.onCanvasPointerOutObservable.clear();
  15060. this.onBeginFrameObservable.clear();
  15061. this.onEndFrameObservable.clear();
  15062. BABYLON.Effect.ResetCache();
  15063. // Abort active requests
  15064. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  15065. var request = _a[_i];
  15066. request.abort();
  15067. }
  15068. };
  15069. // Loading screen
  15070. Engine.prototype.displayLoadingUI = function () {
  15071. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15072. return;
  15073. }
  15074. var loadingScreen = this.loadingScreen;
  15075. if (loadingScreen) {
  15076. loadingScreen.displayLoadingUI();
  15077. }
  15078. };
  15079. Engine.prototype.hideLoadingUI = function () {
  15080. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15081. return;
  15082. }
  15083. var loadingScreen = this.loadingScreen;
  15084. if (loadingScreen) {
  15085. loadingScreen.hideLoadingUI();
  15086. }
  15087. };
  15088. Object.defineProperty(Engine.prototype, "loadingScreen", {
  15089. get: function () {
  15090. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  15091. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  15092. return this._loadingScreen;
  15093. },
  15094. set: function (loadingScreen) {
  15095. this._loadingScreen = loadingScreen;
  15096. },
  15097. enumerable: true,
  15098. configurable: true
  15099. });
  15100. Object.defineProperty(Engine.prototype, "loadingUIText", {
  15101. set: function (text) {
  15102. this.loadingScreen.loadingUIText = text;
  15103. },
  15104. enumerable: true,
  15105. configurable: true
  15106. });
  15107. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  15108. set: function (color) {
  15109. this.loadingScreen.loadingUIBackgroundColor = color;
  15110. },
  15111. enumerable: true,
  15112. configurable: true
  15113. });
  15114. Engine.prototype.attachContextLostEvent = function (callback) {
  15115. if (this._renderingCanvas) {
  15116. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  15117. }
  15118. };
  15119. Engine.prototype.attachContextRestoredEvent = function (callback) {
  15120. if (this._renderingCanvas) {
  15121. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  15122. }
  15123. };
  15124. Engine.prototype.getVertexShaderSource = function (program) {
  15125. var shaders = this._gl.getAttachedShaders(program);
  15126. if (!shaders) {
  15127. return null;
  15128. }
  15129. return this._gl.getShaderSource(shaders[0]);
  15130. };
  15131. Engine.prototype.getFragmentShaderSource = function (program) {
  15132. var shaders = this._gl.getAttachedShaders(program);
  15133. if (!shaders) {
  15134. return null;
  15135. }
  15136. return this._gl.getShaderSource(shaders[1]);
  15137. };
  15138. Engine.prototype.getError = function () {
  15139. return this._gl.getError();
  15140. };
  15141. // FPS
  15142. Engine.prototype.getFps = function () {
  15143. return this._fps;
  15144. };
  15145. Engine.prototype.getDeltaTime = function () {
  15146. return this._deltaTime;
  15147. };
  15148. Engine.prototype._measureFps = function () {
  15149. this._performanceMonitor.sampleFrame();
  15150. this._fps = this._performanceMonitor.averageFPS;
  15151. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  15152. };
  15153. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  15154. if (faceIndex === void 0) { faceIndex = -1; }
  15155. var gl = this._gl;
  15156. if (!this._dummyFramebuffer) {
  15157. var dummy = gl.createFramebuffer();
  15158. if (!dummy) {
  15159. throw new Error("Unable to create dummy framebuffer");
  15160. }
  15161. this._dummyFramebuffer = dummy;
  15162. }
  15163. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  15164. if (faceIndex > -1) {
  15165. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  15166. }
  15167. else {
  15168. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15169. }
  15170. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  15171. var buffer;
  15172. switch (readType) {
  15173. case gl.UNSIGNED_BYTE:
  15174. buffer = new Uint8Array(4 * width * height);
  15175. readType = gl.UNSIGNED_BYTE;
  15176. break;
  15177. default:
  15178. buffer = new Float32Array(4 * width * height);
  15179. readType = gl.FLOAT;
  15180. break;
  15181. }
  15182. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  15183. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  15184. return buffer;
  15185. };
  15186. Engine.prototype._canRenderToFloatFramebuffer = function () {
  15187. if (this._webGLVersion > 1) {
  15188. return this._caps.colorBufferFloat;
  15189. }
  15190. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  15191. };
  15192. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  15193. if (this._webGLVersion > 1) {
  15194. return this._caps.colorBufferFloat;
  15195. }
  15196. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  15197. };
  15198. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  15199. Engine.prototype._canRenderToFramebuffer = function (type) {
  15200. var gl = this._gl;
  15201. //clear existing errors
  15202. while (gl.getError() !== gl.NO_ERROR) { }
  15203. var successful = true;
  15204. var texture = gl.createTexture();
  15205. gl.bindTexture(gl.TEXTURE_2D, texture);
  15206. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15207. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15208. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15209. var fb = gl.createFramebuffer();
  15210. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  15211. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  15212. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  15213. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  15214. successful = successful && (gl.getError() === gl.NO_ERROR);
  15215. //try render by clearing frame buffer's color buffer
  15216. if (successful) {
  15217. gl.clear(gl.COLOR_BUFFER_BIT);
  15218. successful = successful && (gl.getError() === gl.NO_ERROR);
  15219. }
  15220. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  15221. if (successful) {
  15222. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  15223. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15224. var readFormat = gl.RGBA;
  15225. var readType = gl.UNSIGNED_BYTE;
  15226. var buffer = new Uint8Array(4);
  15227. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  15228. successful = successful && (gl.getError() === gl.NO_ERROR);
  15229. }
  15230. //clean up
  15231. gl.deleteTexture(texture);
  15232. gl.deleteFramebuffer(fb);
  15233. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15234. //clear accumulated errors
  15235. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  15236. return successful;
  15237. };
  15238. Engine.prototype._getWebGLTextureType = function (type) {
  15239. if (type === Engine.TEXTURETYPE_FLOAT) {
  15240. return this._gl.FLOAT;
  15241. }
  15242. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15243. // Add Half Float Constant.
  15244. return this._gl.HALF_FLOAT_OES;
  15245. }
  15246. return this._gl.UNSIGNED_BYTE;
  15247. };
  15248. ;
  15249. Engine.prototype._getInternalFormat = function (format) {
  15250. var internalFormat = this._gl.RGBA;
  15251. switch (format) {
  15252. case Engine.TEXTUREFORMAT_ALPHA:
  15253. internalFormat = this._gl.ALPHA;
  15254. break;
  15255. case Engine.TEXTUREFORMAT_LUMINANCE:
  15256. internalFormat = this._gl.LUMINANCE;
  15257. break;
  15258. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  15259. internalFormat = this._gl.LUMINANCE_ALPHA;
  15260. break;
  15261. case Engine.TEXTUREFORMAT_RGB:
  15262. case Engine.TEXTUREFORMAT_RGB32F:
  15263. internalFormat = this._gl.RGB;
  15264. break;
  15265. case Engine.TEXTUREFORMAT_RGBA:
  15266. case Engine.TEXTUREFORMAT_RGBA32F:
  15267. internalFormat = this._gl.RGBA;
  15268. break;
  15269. case Engine.TEXTUREFORMAT_R32F:
  15270. internalFormat = this._gl.RED;
  15271. break;
  15272. case Engine.TEXTUREFORMAT_RG32F:
  15273. internalFormat = this._gl.RG;
  15274. break;
  15275. }
  15276. return internalFormat;
  15277. };
  15278. /** @ignore */
  15279. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  15280. if (this._webGLVersion === 1) {
  15281. if (format) {
  15282. switch (format) {
  15283. case Engine.TEXTUREFORMAT_LUMINANCE:
  15284. return this._gl.LUMINANCE;
  15285. }
  15286. }
  15287. return this._gl.RGBA;
  15288. }
  15289. if (type === Engine.TEXTURETYPE_FLOAT) {
  15290. if (format) {
  15291. switch (format) {
  15292. case Engine.TEXTUREFORMAT_R32F:
  15293. return this._gl.R32F;
  15294. case Engine.TEXTUREFORMAT_RG32F:
  15295. return this._gl.RG32F;
  15296. case Engine.TEXTUREFORMAT_RGB32F:
  15297. return this._gl.RGB32F;
  15298. }
  15299. }
  15300. return this._gl.RGBA32F;
  15301. }
  15302. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15303. return this._gl.RGBA16F;
  15304. }
  15305. if (format) {
  15306. switch (format) {
  15307. case Engine.TEXTUREFORMAT_LUMINANCE:
  15308. return this._gl.LUMINANCE;
  15309. }
  15310. }
  15311. return this._gl.RGBA;
  15312. };
  15313. ;
  15314. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15315. if (type === Engine.TEXTURETYPE_FLOAT) {
  15316. return this._gl.RGBA32F;
  15317. }
  15318. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15319. return this._gl.RGBA16F;
  15320. }
  15321. return this._gl.RGBA8;
  15322. };
  15323. ;
  15324. Engine.prototype.createQuery = function () {
  15325. return this._gl.createQuery();
  15326. };
  15327. Engine.prototype.deleteQuery = function (query) {
  15328. this._gl.deleteQuery(query);
  15329. return this;
  15330. };
  15331. Engine.prototype.isQueryResultAvailable = function (query) {
  15332. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15333. };
  15334. Engine.prototype.getQueryResult = function (query) {
  15335. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15336. };
  15337. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15338. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15339. this._gl.beginQuery(glAlgorithm, query);
  15340. return this;
  15341. };
  15342. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15343. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15344. this._gl.endQuery(glAlgorithm);
  15345. return this;
  15346. };
  15347. /* Time queries */
  15348. Engine.prototype._createTimeQuery = function () {
  15349. var timerQuery = this._caps.timerQuery;
  15350. if (timerQuery.createQueryEXT) {
  15351. return timerQuery.createQueryEXT();
  15352. }
  15353. return this.createQuery();
  15354. };
  15355. Engine.prototype._deleteTimeQuery = function (query) {
  15356. var timerQuery = this._caps.timerQuery;
  15357. if (timerQuery.deleteQueryEXT) {
  15358. timerQuery.deleteQueryEXT(query);
  15359. return;
  15360. }
  15361. this.deleteQuery(query);
  15362. };
  15363. Engine.prototype._getTimeQueryResult = function (query) {
  15364. var timerQuery = this._caps.timerQuery;
  15365. if (timerQuery.getQueryObjectEXT) {
  15366. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15367. }
  15368. return this.getQueryResult(query);
  15369. };
  15370. Engine.prototype._getTimeQueryAvailability = function (query) {
  15371. var timerQuery = this._caps.timerQuery;
  15372. if (timerQuery.getQueryObjectEXT) {
  15373. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15374. }
  15375. return this.isQueryResultAvailable(query);
  15376. };
  15377. Engine.prototype.startTimeQuery = function () {
  15378. var timerQuery = this._caps.timerQuery;
  15379. if (!timerQuery) {
  15380. return null;
  15381. }
  15382. var token = new BABYLON._TimeToken();
  15383. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15384. if (this._caps.canUseTimestampForTimerQuery) {
  15385. token._startTimeQuery = this._createTimeQuery();
  15386. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15387. }
  15388. else {
  15389. if (this._currentNonTimestampToken) {
  15390. return this._currentNonTimestampToken;
  15391. }
  15392. token._timeElapsedQuery = this._createTimeQuery();
  15393. if (timerQuery.beginQueryEXT) {
  15394. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15395. }
  15396. else {
  15397. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15398. }
  15399. this._currentNonTimestampToken = token;
  15400. }
  15401. return token;
  15402. };
  15403. Engine.prototype.endTimeQuery = function (token) {
  15404. var timerQuery = this._caps.timerQuery;
  15405. if (!timerQuery || !token) {
  15406. return -1;
  15407. }
  15408. if (this._caps.canUseTimestampForTimerQuery) {
  15409. if (!token._startTimeQuery) {
  15410. return -1;
  15411. }
  15412. if (!token._endTimeQuery) {
  15413. token._endTimeQuery = this._createTimeQuery();
  15414. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15415. }
  15416. }
  15417. else if (!token._timeElapsedQueryEnded) {
  15418. if (!token._timeElapsedQuery) {
  15419. return -1;
  15420. }
  15421. if (timerQuery.endQueryEXT) {
  15422. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15423. }
  15424. else {
  15425. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15426. }
  15427. token._timeElapsedQueryEnded = true;
  15428. }
  15429. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15430. var available = false;
  15431. if (token._endTimeQuery) {
  15432. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15433. }
  15434. else if (token._timeElapsedQuery) {
  15435. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15436. }
  15437. if (available && !disjoint) {
  15438. var result = 0;
  15439. if (this._caps.canUseTimestampForTimerQuery) {
  15440. if (!token._startTimeQuery || !token._endTimeQuery) {
  15441. return -1;
  15442. }
  15443. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15444. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15445. result = timeEnd - timeStart;
  15446. this._deleteTimeQuery(token._startTimeQuery);
  15447. this._deleteTimeQuery(token._endTimeQuery);
  15448. token._startTimeQuery = null;
  15449. token._endTimeQuery = null;
  15450. }
  15451. else {
  15452. if (!token._timeElapsedQuery) {
  15453. return -1;
  15454. }
  15455. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15456. this._deleteTimeQuery(token._timeElapsedQuery);
  15457. token._timeElapsedQuery = null;
  15458. token._timeElapsedQueryEnded = false;
  15459. this._currentNonTimestampToken = null;
  15460. }
  15461. return result;
  15462. }
  15463. return -1;
  15464. };
  15465. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15466. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15467. };
  15468. // Transform feedback
  15469. Engine.prototype.createTransformFeedback = function () {
  15470. return this._gl.createTransformFeedback();
  15471. };
  15472. Engine.prototype.deleteTransformFeedback = function (value) {
  15473. this._gl.deleteTransformFeedback(value);
  15474. };
  15475. Engine.prototype.bindTransformFeedback = function (value) {
  15476. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15477. };
  15478. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15479. if (usePoints === void 0) { usePoints = true; }
  15480. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15481. };
  15482. Engine.prototype.endTransformFeedback = function () {
  15483. this._gl.endTransformFeedback();
  15484. };
  15485. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15486. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15487. };
  15488. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15489. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15490. };
  15491. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15492. var _this = this;
  15493. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15494. this._activeRequests.push(request);
  15495. request.onCompleteObservable.add(function (request) {
  15496. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15497. });
  15498. return request;
  15499. };
  15500. /** @ignore */
  15501. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15502. var _this = this;
  15503. return new Promise(function (resolve, reject) {
  15504. _this._loadFile(url, function (data) {
  15505. resolve(data);
  15506. }, undefined, database, useArrayBuffer, function (request, exception) {
  15507. reject(exception);
  15508. });
  15509. });
  15510. };
  15511. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15512. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15513. var onload = function (data) {
  15514. loadedFiles[index] = data;
  15515. loadedFiles._internalCount++;
  15516. if (loadedFiles._internalCount === 6) {
  15517. onfinish(loadedFiles);
  15518. }
  15519. };
  15520. var onerror = function (request, exception) {
  15521. if (onErrorCallBack && request) {
  15522. onErrorCallBack(request.status + " " + request.statusText, exception);
  15523. }
  15524. };
  15525. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15526. };
  15527. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15528. if (onError === void 0) { onError = null; }
  15529. var loadedFiles = [];
  15530. loadedFiles._internalCount = 0;
  15531. for (var index = 0; index < 6; index++) {
  15532. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15533. }
  15534. };
  15535. // Statics
  15536. Engine.isSupported = function () {
  15537. try {
  15538. var tempcanvas = document.createElement("canvas");
  15539. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15540. return gl != null && !!window.WebGLRenderingContext;
  15541. }
  15542. catch (e) {
  15543. return false;
  15544. }
  15545. };
  15546. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15547. Engine.ExceptionList = [
  15548. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15549. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15550. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15551. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15552. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15553. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15554. ];
  15555. Engine.Instances = new Array();
  15556. // Const statics
  15557. Engine._ALPHA_DISABLE = 0;
  15558. Engine._ALPHA_ADD = 1;
  15559. Engine._ALPHA_COMBINE = 2;
  15560. Engine._ALPHA_SUBTRACT = 3;
  15561. Engine._ALPHA_MULTIPLY = 4;
  15562. Engine._ALPHA_MAXIMIZED = 5;
  15563. Engine._ALPHA_ONEONE = 6;
  15564. Engine._ALPHA_PREMULTIPLIED = 7;
  15565. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15566. Engine._ALPHA_INTERPOLATE = 9;
  15567. Engine._ALPHA_SCREENMODE = 10;
  15568. Engine._DELAYLOADSTATE_NONE = 0;
  15569. Engine._DELAYLOADSTATE_LOADED = 1;
  15570. Engine._DELAYLOADSTATE_LOADING = 2;
  15571. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15572. Engine._TEXTUREFORMAT_ALPHA = 0;
  15573. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15574. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15575. Engine._TEXTUREFORMAT_RGB = 4;
  15576. Engine._TEXTUREFORMAT_RGBA = 5;
  15577. Engine._TEXTUREFORMAT_R32F = 6;
  15578. Engine._TEXTUREFORMAT_RG32F = 7;
  15579. Engine._TEXTUREFORMAT_RGB32F = 8;
  15580. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15581. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15582. Engine._TEXTURETYPE_FLOAT = 1;
  15583. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15584. // Depht or Stencil test Constants.
  15585. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15586. 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.
  15587. 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.
  15588. 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.
  15589. 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.
  15590. 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.
  15591. 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.
  15592. 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.
  15593. // Stencil Actions Constants.
  15594. Engine._KEEP = 0x1E00;
  15595. Engine._REPLACE = 0x1E01;
  15596. Engine._INCR = 0x1E02;
  15597. Engine._DECR = 0x1E03;
  15598. Engine._INVERT = 0x150A;
  15599. Engine._INCR_WRAP = 0x8507;
  15600. Engine._DECR_WRAP = 0x8508;
  15601. // Texture rescaling mode
  15602. Engine._SCALEMODE_FLOOR = 1;
  15603. Engine._SCALEMODE_NEAREST = 2;
  15604. Engine._SCALEMODE_CEILING = 3;
  15605. // Updatable statics so stick with vars here
  15606. Engine.CollisionsEpsilon = 0.001;
  15607. Engine.CodeRepository = "src/";
  15608. Engine.ShadersRepository = "src/Shaders/";
  15609. return Engine;
  15610. }());
  15611. BABYLON.Engine = Engine;
  15612. })(BABYLON || (BABYLON = {}));
  15613. //# sourceMappingURL=babylon.engine.js.map
  15614. var BABYLON;
  15615. (function (BABYLON) {
  15616. /**
  15617. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15618. */
  15619. var Node = /** @class */ (function () {
  15620. /**
  15621. * Creates a new Node
  15622. * @param {string} name - the name and id to be given to this node
  15623. * @param {BABYLON.Scene} the scene this node will be added to
  15624. */
  15625. function Node(name, scene) {
  15626. if (scene === void 0) { scene = null; }
  15627. /**
  15628. * Gets or sets a string used to store user defined state for the node
  15629. */
  15630. this.state = "";
  15631. /**
  15632. * Gets or sets an object used to store user defined information for the node
  15633. */
  15634. this.metadata = null;
  15635. /**
  15636. * Gets or sets a boolean used to define if the node must be serialized
  15637. */
  15638. this.doNotSerialize = false;
  15639. /** @ignore */
  15640. this._isDisposed = false;
  15641. /**
  15642. * Gets a list of {BABYLON.Animation} associated with the node
  15643. */
  15644. this.animations = new Array();
  15645. this._ranges = {};
  15646. this._isEnabled = true;
  15647. this._isReady = true;
  15648. /** @ignore */
  15649. this._currentRenderId = -1;
  15650. this._parentRenderId = -1;
  15651. this._animationPropertiesOverride = null;
  15652. /**
  15653. * An event triggered when the mesh is disposed
  15654. * @type {BABYLON.Observable}
  15655. */
  15656. this.onDisposeObservable = new BABYLON.Observable();
  15657. // Behaviors
  15658. this._behaviors = new Array();
  15659. this.name = name;
  15660. this.id = name;
  15661. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15662. this.uniqueId = this._scene.getUniqueId();
  15663. this._initCache();
  15664. }
  15665. /**
  15666. * Gets a boolean indicating if the node has been disposed
  15667. * @returns true if the node was disposed
  15668. */
  15669. Node.prototype.isDisposed = function () {
  15670. return this._isDisposed;
  15671. };
  15672. Object.defineProperty(Node.prototype, "parent", {
  15673. get: function () {
  15674. return this._parentNode;
  15675. },
  15676. /**
  15677. * Gets or sets the parent of the node
  15678. */
  15679. set: function (parent) {
  15680. if (this._parentNode === parent) {
  15681. return;
  15682. }
  15683. // Remove self from list of children of parent
  15684. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15685. var index = this._parentNode._children.indexOf(this);
  15686. if (index !== -1) {
  15687. this._parentNode._children.splice(index, 1);
  15688. }
  15689. }
  15690. // Store new parent
  15691. this._parentNode = parent;
  15692. // Add as child to new parent
  15693. if (this._parentNode) {
  15694. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15695. this._parentNode._children = new Array();
  15696. }
  15697. this._parentNode._children.push(this);
  15698. }
  15699. },
  15700. enumerable: true,
  15701. configurable: true
  15702. });
  15703. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  15704. /**
  15705. * Gets or sets the animation properties override
  15706. */
  15707. get: function () {
  15708. return this._animationPropertiesOverride;
  15709. },
  15710. set: function (value) {
  15711. this._animationPropertiesOverride = value;
  15712. },
  15713. enumerable: true,
  15714. configurable: true
  15715. });
  15716. /**
  15717. * Gets a string idenfifying the name of the class
  15718. * @returns "Node" string
  15719. */
  15720. Node.prototype.getClassName = function () {
  15721. return "Node";
  15722. };
  15723. Object.defineProperty(Node.prototype, "onDispose", {
  15724. /**
  15725. * Sets a callback that will be raised when the node will be disposed
  15726. */
  15727. set: function (callback) {
  15728. if (this._onDisposeObserver) {
  15729. this.onDisposeObservable.remove(this._onDisposeObserver);
  15730. }
  15731. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15732. },
  15733. enumerable: true,
  15734. configurable: true
  15735. });
  15736. /**
  15737. * Gets the scene of the node
  15738. * @returns a {BABYLON.Scene}
  15739. */
  15740. Node.prototype.getScene = function () {
  15741. return this._scene;
  15742. };
  15743. /**
  15744. * Gets the engine of the node
  15745. * @returns a {BABYLON.Engine}
  15746. */
  15747. Node.prototype.getEngine = function () {
  15748. return this._scene.getEngine();
  15749. };
  15750. /**
  15751. * Attach a behavior to the node
  15752. * @see http://doc.babylonjs.com/features/behaviour
  15753. * @param behavior defines the behavior to attach
  15754. * @returns the current Node
  15755. */
  15756. Node.prototype.addBehavior = function (behavior) {
  15757. var _this = this;
  15758. var index = this._behaviors.indexOf(behavior);
  15759. if (index !== -1) {
  15760. return this;
  15761. }
  15762. behavior.init();
  15763. if (this._scene.isLoading) {
  15764. // We defer the attach when the scene will be loaded
  15765. var observer = this._scene.onDataLoadedObservable.add(function () {
  15766. behavior.attach(_this);
  15767. setTimeout(function () {
  15768. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15769. _this._scene.onDataLoadedObservable.remove(observer);
  15770. }, 0);
  15771. });
  15772. }
  15773. else {
  15774. behavior.attach(this);
  15775. }
  15776. this._behaviors.push(behavior);
  15777. return this;
  15778. };
  15779. /**
  15780. * Remove an attached behavior
  15781. * @see http://doc.babylonjs.com/features/behaviour
  15782. * @param behavior defines the behavior to attach
  15783. * @returns the current Node
  15784. */
  15785. Node.prototype.removeBehavior = function (behavior) {
  15786. var index = this._behaviors.indexOf(behavior);
  15787. if (index === -1) {
  15788. return this;
  15789. }
  15790. this._behaviors[index].detach();
  15791. this._behaviors.splice(index, 1);
  15792. return this;
  15793. };
  15794. Object.defineProperty(Node.prototype, "behaviors", {
  15795. /**
  15796. * Gets the list of attached behaviors
  15797. * @see http://doc.babylonjs.com/features/behaviour
  15798. */
  15799. get: function () {
  15800. return this._behaviors;
  15801. },
  15802. enumerable: true,
  15803. configurable: true
  15804. });
  15805. /**
  15806. * Gets an attached behavior by name
  15807. * @param name defines the name of the behavior to look for
  15808. * @see http://doc.babylonjs.com/features/behaviour
  15809. * @returns null if behavior was not found else the requested behavior
  15810. */
  15811. Node.prototype.getBehaviorByName = function (name) {
  15812. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15813. var behavior = _a[_i];
  15814. if (behavior.name === name) {
  15815. return behavior;
  15816. }
  15817. }
  15818. return null;
  15819. };
  15820. /**
  15821. * Returns the world matrix of the node
  15822. * @returns a matrix containing the node's world matrix
  15823. */
  15824. Node.prototype.getWorldMatrix = function () {
  15825. return BABYLON.Matrix.Identity();
  15826. };
  15827. // override it in derived class if you add new variables to the cache
  15828. // and call the parent class method
  15829. /** @ignore */
  15830. Node.prototype._initCache = function () {
  15831. this._cache = {};
  15832. this._cache.parent = undefined;
  15833. };
  15834. /** @ignore */
  15835. Node.prototype.updateCache = function (force) {
  15836. if (!force && this.isSynchronized())
  15837. return;
  15838. this._cache.parent = this.parent;
  15839. this._updateCache();
  15840. };
  15841. // override it in derived class if you add new variables to the cache
  15842. // and call the parent class method if !ignoreParentClass
  15843. /** @ignore */
  15844. Node.prototype._updateCache = function (ignoreParentClass) {
  15845. };
  15846. // override it in derived class if you add new variables to the cache
  15847. /** @ignore */
  15848. Node.prototype._isSynchronized = function () {
  15849. return true;
  15850. };
  15851. /** @ignore */
  15852. Node.prototype._markSyncedWithParent = function () {
  15853. if (this.parent) {
  15854. this._parentRenderId = this.parent._currentRenderId;
  15855. }
  15856. };
  15857. /** @ignore */
  15858. Node.prototype.isSynchronizedWithParent = function () {
  15859. if (!this.parent) {
  15860. return true;
  15861. }
  15862. if (this._parentRenderId !== this.parent._currentRenderId) {
  15863. return false;
  15864. }
  15865. return this.parent.isSynchronized();
  15866. };
  15867. /** @ignore */
  15868. Node.prototype.isSynchronized = function (updateCache) {
  15869. var check = this.hasNewParent();
  15870. check = check || !this.isSynchronizedWithParent();
  15871. check = check || !this._isSynchronized();
  15872. if (updateCache)
  15873. this.updateCache(true);
  15874. return !check;
  15875. };
  15876. /** @ignore */
  15877. Node.prototype.hasNewParent = function (update) {
  15878. if (this._cache.parent === this.parent)
  15879. return false;
  15880. if (update)
  15881. this._cache.parent = this.parent;
  15882. return true;
  15883. };
  15884. /**
  15885. * Is this node ready to be used/rendered
  15886. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15887. * @return true if the node is ready
  15888. */
  15889. Node.prototype.isReady = function (completeCheck) {
  15890. if (completeCheck === void 0) { completeCheck = false; }
  15891. return this._isReady;
  15892. };
  15893. /**
  15894. * Is this node enabled?
  15895. * 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
  15896. * @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
  15897. * @return whether this node (and its parent) is enabled
  15898. * @see setEnabled
  15899. */
  15900. Node.prototype.isEnabled = function (checkAncestors) {
  15901. if (checkAncestors === void 0) { checkAncestors = true; }
  15902. if (checkAncestors === false) {
  15903. return this._isEnabled;
  15904. }
  15905. if (this._isEnabled === false) {
  15906. return false;
  15907. }
  15908. if (this.parent !== undefined && this.parent !== null) {
  15909. return this.parent.isEnabled(checkAncestors);
  15910. }
  15911. return true;
  15912. };
  15913. /**
  15914. * Set the enabled state of this node
  15915. * @param value defines the new enabled state
  15916. * @see isEnabled
  15917. */
  15918. Node.prototype.setEnabled = function (value) {
  15919. this._isEnabled = value;
  15920. };
  15921. /**
  15922. * Is this node a descendant of the given node?
  15923. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15924. * @param ancestor defines the parent node to inspect
  15925. * @see parent
  15926. * @returns a boolean indicating if this node is a descendant of the given node
  15927. */
  15928. Node.prototype.isDescendantOf = function (ancestor) {
  15929. if (this.parent) {
  15930. if (this.parent === ancestor) {
  15931. return true;
  15932. }
  15933. return this.parent.isDescendantOf(ancestor);
  15934. }
  15935. return false;
  15936. };
  15937. /** @ignore */
  15938. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15939. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15940. if (!this._children) {
  15941. return;
  15942. }
  15943. for (var index = 0; index < this._children.length; index++) {
  15944. var item = this._children[index];
  15945. if (!predicate || predicate(item)) {
  15946. results.push(item);
  15947. }
  15948. if (!directDescendantsOnly) {
  15949. item._getDescendants(results, false, predicate);
  15950. }
  15951. }
  15952. };
  15953. /**
  15954. * Will return all nodes that have this node as ascendant
  15955. * @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
  15956. * @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
  15957. * @return all children nodes of all types
  15958. */
  15959. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15960. var results = new Array();
  15961. this._getDescendants(results, directDescendantsOnly, predicate);
  15962. return results;
  15963. };
  15964. /**
  15965. * Get all child-meshes of this node
  15966. * @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
  15967. * @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
  15968. * @returns an array of {BABYLON.AbstractMesh}
  15969. */
  15970. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15971. var results = [];
  15972. this._getDescendants(results, directDescendantsOnly, function (node) {
  15973. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15974. });
  15975. return results;
  15976. };
  15977. /**
  15978. * Get all child-transformNodes of this node
  15979. * @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
  15980. * @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
  15981. * @returns an array of {BABYLON.TransformNode}
  15982. */
  15983. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15984. var results = [];
  15985. this._getDescendants(results, directDescendantsOnly, function (node) {
  15986. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15987. });
  15988. return results;
  15989. };
  15990. /**
  15991. * Get all direct children of this node
  15992. * @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
  15993. * @returns an array of {BABYLON.Node}
  15994. */
  15995. Node.prototype.getChildren = function (predicate) {
  15996. return this.getDescendants(true, predicate);
  15997. };
  15998. /** @ignore */
  15999. Node.prototype._setReady = function (state) {
  16000. if (state === this._isReady) {
  16001. return;
  16002. }
  16003. if (!state) {
  16004. this._isReady = false;
  16005. return;
  16006. }
  16007. if (this.onReady) {
  16008. this.onReady(this);
  16009. }
  16010. this._isReady = true;
  16011. };
  16012. /**
  16013. * Get an animation by name
  16014. * @param name defines the name of the animation to look for
  16015. * @returns null if not found else the requested animation
  16016. */
  16017. Node.prototype.getAnimationByName = function (name) {
  16018. for (var i = 0; i < this.animations.length; i++) {
  16019. var animation = this.animations[i];
  16020. if (animation.name === name) {
  16021. return animation;
  16022. }
  16023. }
  16024. return null;
  16025. };
  16026. /**
  16027. * Creates an animation range for this node
  16028. * @param name defines the name of the range
  16029. * @param from defines the starting key
  16030. * @param to defines the end key
  16031. */
  16032. Node.prototype.createAnimationRange = function (name, from, to) {
  16033. // check name not already in use
  16034. if (!this._ranges[name]) {
  16035. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  16036. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16037. if (this.animations[i]) {
  16038. this.animations[i].createRange(name, from, to);
  16039. }
  16040. }
  16041. }
  16042. };
  16043. /**
  16044. * Delete a specific animation range
  16045. * @param name defines the name of the range to delete
  16046. * @param deleteFrames defines if animation frames from the range must be deleted as well
  16047. */
  16048. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  16049. if (deleteFrames === void 0) { deleteFrames = true; }
  16050. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16051. if (this.animations[i]) {
  16052. this.animations[i].deleteRange(name, deleteFrames);
  16053. }
  16054. }
  16055. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  16056. };
  16057. /**
  16058. * Get an animation range by name
  16059. * @param name defines the name of the animation range to look for
  16060. * @returns null if not found else the requested animation range
  16061. */
  16062. Node.prototype.getAnimationRange = function (name) {
  16063. return this._ranges[name];
  16064. };
  16065. /**
  16066. * Will start the animation sequence
  16067. * @param name defines the range frames for animation sequence
  16068. * @param loop defines if the animation should loop (false by default)
  16069. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  16070. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  16071. * @returns the object created for this animation. If range does not exist, it will return null
  16072. */
  16073. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  16074. var range = this.getAnimationRange(name);
  16075. if (!range) {
  16076. return null;
  16077. }
  16078. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  16079. };
  16080. /**
  16081. * Serialize animation ranges into a JSON compatible object
  16082. * @returns serialization object
  16083. */
  16084. Node.prototype.serializeAnimationRanges = function () {
  16085. var serializationRanges = [];
  16086. for (var name in this._ranges) {
  16087. var localRange = this._ranges[name];
  16088. if (!localRange) {
  16089. continue;
  16090. }
  16091. var range = {};
  16092. range.name = name;
  16093. range.from = localRange.from;
  16094. range.to = localRange.to;
  16095. serializationRanges.push(range);
  16096. }
  16097. return serializationRanges;
  16098. };
  16099. /**
  16100. * Computes the world matrix of the node
  16101. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  16102. * @returns the world matrix
  16103. */
  16104. Node.prototype.computeWorldMatrix = function (force) {
  16105. return BABYLON.Matrix.Identity();
  16106. };
  16107. /**
  16108. * Releases resources associated with this node.
  16109. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  16110. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  16111. */
  16112. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16113. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16114. if (!doNotRecurse) {
  16115. var nodes = this.getDescendants(true);
  16116. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  16117. var node = nodes_1[_i];
  16118. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  16119. }
  16120. }
  16121. else {
  16122. var transformNodes = this.getChildTransformNodes(true);
  16123. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  16124. var transformNode = transformNodes_1[_a];
  16125. transformNode.parent = null;
  16126. transformNode.computeWorldMatrix(true);
  16127. }
  16128. }
  16129. this.parent = null;
  16130. // Callback
  16131. this.onDisposeObservable.notifyObservers(this);
  16132. this.onDisposeObservable.clear();
  16133. // Behaviors
  16134. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  16135. var behavior = _c[_b];
  16136. behavior.detach();
  16137. }
  16138. this._behaviors = [];
  16139. this._isDisposed = true;
  16140. };
  16141. /**
  16142. * Parse animation range data from a serialization object and store them into a given node
  16143. * @param node defines where to store the animation ranges
  16144. * @param parsedNode defines the serialization object to read data from
  16145. * @param scene defines the hosting scene
  16146. */
  16147. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  16148. if (parsedNode.ranges) {
  16149. for (var index = 0; index < parsedNode.ranges.length; index++) {
  16150. var data = parsedNode.ranges[index];
  16151. node.createAnimationRange(data.name, data.from, data.to);
  16152. }
  16153. }
  16154. };
  16155. __decorate([
  16156. BABYLON.serialize()
  16157. ], Node.prototype, "name", void 0);
  16158. __decorate([
  16159. BABYLON.serialize()
  16160. ], Node.prototype, "id", void 0);
  16161. __decorate([
  16162. BABYLON.serialize()
  16163. ], Node.prototype, "uniqueId", void 0);
  16164. __decorate([
  16165. BABYLON.serialize()
  16166. ], Node.prototype, "state", void 0);
  16167. __decorate([
  16168. BABYLON.serialize()
  16169. ], Node.prototype, "metadata", void 0);
  16170. return Node;
  16171. }());
  16172. BABYLON.Node = Node;
  16173. })(BABYLON || (BABYLON = {}));
  16174. //# sourceMappingURL=babylon.node.js.map
  16175. var BABYLON;
  16176. (function (BABYLON) {
  16177. var BoundingSphere = /** @class */ (function () {
  16178. function BoundingSphere(minimum, maximum) {
  16179. this.minimum = minimum;
  16180. this.maximum = maximum;
  16181. this._tempRadiusVector = BABYLON.Vector3.Zero();
  16182. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  16183. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  16184. this.radius = distance * 0.5;
  16185. this.centerWorld = BABYLON.Vector3.Zero();
  16186. this._update(BABYLON.Matrix.Identity());
  16187. }
  16188. // Methods
  16189. BoundingSphere.prototype._update = function (world) {
  16190. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  16191. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  16192. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  16193. };
  16194. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  16195. for (var i = 0; i < 6; i++) {
  16196. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  16197. return false;
  16198. }
  16199. return true;
  16200. };
  16201. BoundingSphere.prototype.intersectsPoint = function (point) {
  16202. var x = this.centerWorld.x - point.x;
  16203. var y = this.centerWorld.y - point.y;
  16204. var z = this.centerWorld.z - point.z;
  16205. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16206. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  16207. return false;
  16208. return true;
  16209. };
  16210. // Statics
  16211. BoundingSphere.Intersects = function (sphere0, sphere1) {
  16212. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  16213. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  16214. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  16215. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16216. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  16217. return false;
  16218. return true;
  16219. };
  16220. return BoundingSphere;
  16221. }());
  16222. BABYLON.BoundingSphere = BoundingSphere;
  16223. })(BABYLON || (BABYLON = {}));
  16224. //# sourceMappingURL=babylon.boundingSphere.js.map
  16225. var BABYLON;
  16226. (function (BABYLON) {
  16227. var BoundingBox = /** @class */ (function () {
  16228. function BoundingBox(minimum, maximum) {
  16229. this.minimum = minimum;
  16230. this.maximum = maximum;
  16231. this.vectors = new Array();
  16232. this.vectorsWorld = new Array();
  16233. // Bounding vectors
  16234. this.vectors.push(this.minimum.clone());
  16235. this.vectors.push(this.maximum.clone());
  16236. this.vectors.push(this.minimum.clone());
  16237. this.vectors[2].x = this.maximum.x;
  16238. this.vectors.push(this.minimum.clone());
  16239. this.vectors[3].y = this.maximum.y;
  16240. this.vectors.push(this.minimum.clone());
  16241. this.vectors[4].z = this.maximum.z;
  16242. this.vectors.push(this.maximum.clone());
  16243. this.vectors[5].z = this.minimum.z;
  16244. this.vectors.push(this.maximum.clone());
  16245. this.vectors[6].x = this.minimum.x;
  16246. this.vectors.push(this.maximum.clone());
  16247. this.vectors[7].y = this.minimum.y;
  16248. // OBB
  16249. this.center = this.maximum.add(this.minimum).scale(0.5);
  16250. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  16251. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  16252. // World
  16253. for (var index = 0; index < this.vectors.length; index++) {
  16254. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  16255. }
  16256. this.minimumWorld = BABYLON.Vector3.Zero();
  16257. this.maximumWorld = BABYLON.Vector3.Zero();
  16258. this.centerWorld = BABYLON.Vector3.Zero();
  16259. this.extendSizeWorld = BABYLON.Vector3.Zero();
  16260. this._update(BABYLON.Matrix.Identity());
  16261. }
  16262. // Methods
  16263. BoundingBox.prototype.getWorldMatrix = function () {
  16264. return this._worldMatrix;
  16265. };
  16266. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  16267. this._worldMatrix.copyFrom(matrix);
  16268. return this;
  16269. };
  16270. BoundingBox.prototype._update = function (world) {
  16271. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  16272. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  16273. for (var index = 0; index < this.vectors.length; index++) {
  16274. var v = this.vectorsWorld[index];
  16275. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  16276. if (v.x < this.minimumWorld.x)
  16277. this.minimumWorld.x = v.x;
  16278. if (v.y < this.minimumWorld.y)
  16279. this.minimumWorld.y = v.y;
  16280. if (v.z < this.minimumWorld.z)
  16281. this.minimumWorld.z = v.z;
  16282. if (v.x > this.maximumWorld.x)
  16283. this.maximumWorld.x = v.x;
  16284. if (v.y > this.maximumWorld.y)
  16285. this.maximumWorld.y = v.y;
  16286. if (v.z > this.maximumWorld.z)
  16287. this.maximumWorld.z = v.z;
  16288. }
  16289. // Extend
  16290. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  16291. this.extendSizeWorld.scaleInPlace(0.5);
  16292. // OBB
  16293. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  16294. this.centerWorld.scaleInPlace(0.5);
  16295. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  16296. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  16297. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  16298. this._worldMatrix = world;
  16299. };
  16300. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  16301. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  16302. };
  16303. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16304. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  16305. };
  16306. BoundingBox.prototype.intersectsPoint = function (point) {
  16307. var delta = -BABYLON.Epsilon;
  16308. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  16309. return false;
  16310. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  16311. return false;
  16312. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  16313. return false;
  16314. return true;
  16315. };
  16316. BoundingBox.prototype.intersectsSphere = function (sphere) {
  16317. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  16318. };
  16319. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  16320. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  16321. return false;
  16322. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  16323. return false;
  16324. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  16325. return false;
  16326. return true;
  16327. };
  16328. // Statics
  16329. BoundingBox.Intersects = function (box0, box1) {
  16330. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16331. return false;
  16332. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16333. return false;
  16334. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16335. return false;
  16336. return true;
  16337. };
  16338. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16339. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16340. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16341. return (num <= (sphereRadius * sphereRadius));
  16342. };
  16343. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16344. for (var p = 0; p < 6; p++) {
  16345. for (var i = 0; i < 8; i++) {
  16346. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16347. return false;
  16348. }
  16349. }
  16350. }
  16351. return true;
  16352. };
  16353. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16354. for (var p = 0; p < 6; p++) {
  16355. var inCount = 8;
  16356. for (var i = 0; i < 8; i++) {
  16357. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16358. --inCount;
  16359. }
  16360. else {
  16361. break;
  16362. }
  16363. }
  16364. if (inCount === 0)
  16365. return false;
  16366. }
  16367. return true;
  16368. };
  16369. return BoundingBox;
  16370. }());
  16371. BABYLON.BoundingBox = BoundingBox;
  16372. })(BABYLON || (BABYLON = {}));
  16373. //# sourceMappingURL=babylon.boundingBox.js.map
  16374. var BABYLON;
  16375. (function (BABYLON) {
  16376. var computeBoxExtents = function (axis, box) {
  16377. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16378. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16379. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16380. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16381. var r = r0 + r1 + r2;
  16382. return {
  16383. min: p - r,
  16384. max: p + r
  16385. };
  16386. };
  16387. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16388. var axisOverlap = function (axis, box0, box1) {
  16389. var result0 = computeBoxExtents(axis, box0);
  16390. var result1 = computeBoxExtents(axis, box1);
  16391. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16392. };
  16393. var BoundingInfo = /** @class */ (function () {
  16394. function BoundingInfo(minimum, maximum) {
  16395. this.minimum = minimum;
  16396. this.maximum = maximum;
  16397. this._isLocked = false;
  16398. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16399. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16400. }
  16401. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16402. get: function () {
  16403. return this._isLocked;
  16404. },
  16405. set: function (value) {
  16406. this._isLocked = value;
  16407. },
  16408. enumerable: true,
  16409. configurable: true
  16410. });
  16411. // Methods
  16412. BoundingInfo.prototype.update = function (world) {
  16413. if (this._isLocked) {
  16414. return;
  16415. }
  16416. this.boundingBox._update(world);
  16417. this.boundingSphere._update(world);
  16418. };
  16419. /**
  16420. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16421. * @param center New center of the bounding info
  16422. * @param extend New extend of the bounding info
  16423. */
  16424. BoundingInfo.prototype.centerOn = function (center, extend) {
  16425. this.minimum = center.subtract(extend);
  16426. this.maximum = center.add(extend);
  16427. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16428. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16429. return this;
  16430. };
  16431. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16432. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16433. return false;
  16434. return this.boundingBox.isInFrustum(frustumPlanes);
  16435. };
  16436. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16437. /**
  16438. * Gets the world distance between the min and max points of the bounding box
  16439. */
  16440. get: function () {
  16441. var boundingBox = this.boundingBox;
  16442. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16443. return size.length();
  16444. },
  16445. enumerable: true,
  16446. configurable: true
  16447. });
  16448. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16449. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16450. };
  16451. BoundingInfo.prototype._checkCollision = function (collider) {
  16452. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16453. };
  16454. BoundingInfo.prototype.intersectsPoint = function (point) {
  16455. if (!this.boundingSphere.centerWorld) {
  16456. return false;
  16457. }
  16458. if (!this.boundingSphere.intersectsPoint(point)) {
  16459. return false;
  16460. }
  16461. if (!this.boundingBox.intersectsPoint(point)) {
  16462. return false;
  16463. }
  16464. return true;
  16465. };
  16466. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16467. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16468. return false;
  16469. }
  16470. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16471. return false;
  16472. }
  16473. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16474. return false;
  16475. }
  16476. if (!precise) {
  16477. return true;
  16478. }
  16479. var box0 = this.boundingBox;
  16480. var box1 = boundingInfo.boundingBox;
  16481. if (!axisOverlap(box0.directions[0], box0, box1))
  16482. return false;
  16483. if (!axisOverlap(box0.directions[1], box0, box1))
  16484. return false;
  16485. if (!axisOverlap(box0.directions[2], box0, box1))
  16486. return false;
  16487. if (!axisOverlap(box1.directions[0], box0, box1))
  16488. return false;
  16489. if (!axisOverlap(box1.directions[1], box0, box1))
  16490. return false;
  16491. if (!axisOverlap(box1.directions[2], box0, box1))
  16492. return false;
  16493. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16494. return false;
  16495. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16496. return false;
  16497. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16498. return false;
  16499. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16500. return false;
  16501. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16502. return false;
  16503. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16504. return false;
  16505. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16506. return false;
  16507. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16508. return false;
  16509. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16510. return false;
  16511. return true;
  16512. };
  16513. return BoundingInfo;
  16514. }());
  16515. BABYLON.BoundingInfo = BoundingInfo;
  16516. })(BABYLON || (BABYLON = {}));
  16517. //# sourceMappingURL=babylon.boundingInfo.js.map
  16518. var BABYLON;
  16519. (function (BABYLON) {
  16520. var TransformNode = /** @class */ (function (_super) {
  16521. __extends(TransformNode, _super);
  16522. function TransformNode(name, scene, isPure) {
  16523. if (scene === void 0) { scene = null; }
  16524. if (isPure === void 0) { isPure = true; }
  16525. var _this = _super.call(this, name, scene) || this;
  16526. // Properties
  16527. _this._rotation = BABYLON.Vector3.Zero();
  16528. _this._scaling = BABYLON.Vector3.One();
  16529. _this._isDirty = false;
  16530. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  16531. _this.scalingDeterminant = 1;
  16532. _this.infiniteDistance = false;
  16533. _this.position = BABYLON.Vector3.Zero();
  16534. _this._localWorld = BABYLON.Matrix.Zero();
  16535. _this._worldMatrix = BABYLON.Matrix.Zero();
  16536. _this._worldMatrixDeterminant = 0;
  16537. _this._absolutePosition = BABYLON.Vector3.Zero();
  16538. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16539. _this._postMultiplyPivotMatrix = false;
  16540. _this._isWorldMatrixFrozen = false;
  16541. /**
  16542. * An event triggered after the world matrix is updated
  16543. * @type {BABYLON.Observable}
  16544. */
  16545. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16546. _this._nonUniformScaling = false;
  16547. if (isPure) {
  16548. _this.getScene().addTransformNode(_this);
  16549. }
  16550. return _this;
  16551. }
  16552. /**
  16553. * Gets a string idenfifying the name of the class
  16554. * @returns "TransformNode" string
  16555. */
  16556. TransformNode.prototype.getClassName = function () {
  16557. return "TransformNode";
  16558. };
  16559. Object.defineProperty(TransformNode.prototype, "rotation", {
  16560. /**
  16561. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16562. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16563. * Default : (0.0, 0.0, 0.0)
  16564. */
  16565. get: function () {
  16566. return this._rotation;
  16567. },
  16568. set: function (newRotation) {
  16569. this._rotation = newRotation;
  16570. },
  16571. enumerable: true,
  16572. configurable: true
  16573. });
  16574. Object.defineProperty(TransformNode.prototype, "scaling", {
  16575. /**
  16576. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16577. * Default : (1.0, 1.0, 1.0)
  16578. */
  16579. get: function () {
  16580. return this._scaling;
  16581. },
  16582. /**
  16583. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16584. * Default : (1.0, 1.0, 1.0)
  16585. */
  16586. set: function (newScaling) {
  16587. this._scaling = newScaling;
  16588. },
  16589. enumerable: true,
  16590. configurable: true
  16591. });
  16592. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16593. /**
  16594. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16595. * It's null by default.
  16596. * 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)
  16597. */
  16598. get: function () {
  16599. return this._rotationQuaternion;
  16600. },
  16601. set: function (quaternion) {
  16602. this._rotationQuaternion = quaternion;
  16603. //reset the rotation vector.
  16604. if (quaternion && this.rotation.length()) {
  16605. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16606. }
  16607. },
  16608. enumerable: true,
  16609. configurable: true
  16610. });
  16611. /**
  16612. * Returns the latest update of the World matrix
  16613. * Returns a Matrix.
  16614. */
  16615. TransformNode.prototype.getWorldMatrix = function () {
  16616. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16617. this.computeWorldMatrix();
  16618. }
  16619. return this._worldMatrix;
  16620. };
  16621. /**
  16622. * Returns the latest update of the World matrix determinant.
  16623. */
  16624. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16625. return this._worldMatrixDeterminant;
  16626. };
  16627. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16628. /**
  16629. * Returns directly the latest state of the mesh World matrix.
  16630. * A Matrix is returned.
  16631. */
  16632. get: function () {
  16633. return this._worldMatrix;
  16634. },
  16635. enumerable: true,
  16636. configurable: true
  16637. });
  16638. /**
  16639. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16640. * Returns the AbstractMesh.
  16641. */
  16642. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16643. this._poseMatrix.copyFrom(matrix);
  16644. return this;
  16645. };
  16646. /**
  16647. * Returns the mesh Pose matrix.
  16648. * Returned object : Matrix
  16649. */
  16650. TransformNode.prototype.getPoseMatrix = function () {
  16651. return this._poseMatrix;
  16652. };
  16653. TransformNode.prototype._isSynchronized = function () {
  16654. if (this._isDirty) {
  16655. return false;
  16656. }
  16657. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  16658. return false;
  16659. if (this._cache.pivotMatrixUpdated) {
  16660. return false;
  16661. }
  16662. if (this.infiniteDistance) {
  16663. return false;
  16664. }
  16665. if (!this._cache.position.equals(this.position))
  16666. return false;
  16667. if (this.rotationQuaternion) {
  16668. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16669. return false;
  16670. }
  16671. if (!this._cache.rotation.equals(this.rotation))
  16672. return false;
  16673. if (!this._cache.scaling.equals(this.scaling))
  16674. return false;
  16675. return true;
  16676. };
  16677. TransformNode.prototype._initCache = function () {
  16678. _super.prototype._initCache.call(this);
  16679. this._cache.localMatrixUpdated = false;
  16680. this._cache.position = BABYLON.Vector3.Zero();
  16681. this._cache.scaling = BABYLON.Vector3.Zero();
  16682. this._cache.rotation = BABYLON.Vector3.Zero();
  16683. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16684. this._cache.billboardMode = -1;
  16685. };
  16686. TransformNode.prototype.markAsDirty = function (property) {
  16687. if (property === "rotation") {
  16688. this.rotationQuaternion = null;
  16689. }
  16690. this._currentRenderId = Number.MAX_VALUE;
  16691. this._isDirty = true;
  16692. return this;
  16693. };
  16694. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16695. /**
  16696. * Returns the current mesh absolute position.
  16697. * Retuns a Vector3.
  16698. */
  16699. get: function () {
  16700. return this._absolutePosition;
  16701. },
  16702. enumerable: true,
  16703. configurable: true
  16704. });
  16705. /**
  16706. * Sets a new matrix to apply before all other transformation
  16707. * @param matrix defines the transform matrix
  16708. * @returns the current TransformNode
  16709. */
  16710. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16711. return this.setPivotMatrix(matrix, false);
  16712. };
  16713. /**
  16714. * Sets a new pivot matrix to the current node
  16715. * @param matrix defines the new pivot matrix to use
  16716. * @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
  16717. * @returns the current TransformNode
  16718. */
  16719. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16720. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16721. this._pivotMatrix = matrix.clone();
  16722. this._cache.pivotMatrixUpdated = true;
  16723. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16724. if (this._postMultiplyPivotMatrix) {
  16725. if (!this._pivotMatrixInverse) {
  16726. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16727. }
  16728. else {
  16729. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16730. }
  16731. }
  16732. return this;
  16733. };
  16734. /**
  16735. * Returns the mesh pivot matrix.
  16736. * Default : Identity.
  16737. * A Matrix is returned.
  16738. */
  16739. TransformNode.prototype.getPivotMatrix = function () {
  16740. return this._pivotMatrix;
  16741. };
  16742. /**
  16743. * Prevents the World matrix to be computed any longer.
  16744. * Returns the AbstractMesh.
  16745. */
  16746. TransformNode.prototype.freezeWorldMatrix = function () {
  16747. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16748. this.computeWorldMatrix(true);
  16749. this._isWorldMatrixFrozen = true;
  16750. return this;
  16751. };
  16752. /**
  16753. * Allows back the World matrix computation.
  16754. * Returns the AbstractMesh.
  16755. */
  16756. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16757. this._isWorldMatrixFrozen = false;
  16758. this.computeWorldMatrix(true);
  16759. return this;
  16760. };
  16761. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16762. /**
  16763. * True if the World matrix has been frozen.
  16764. * Returns a boolean.
  16765. */
  16766. get: function () {
  16767. return this._isWorldMatrixFrozen;
  16768. },
  16769. enumerable: true,
  16770. configurable: true
  16771. });
  16772. /**
  16773. * Retuns the mesh absolute position in the World.
  16774. * Returns a Vector3.
  16775. */
  16776. TransformNode.prototype.getAbsolutePosition = function () {
  16777. this.computeWorldMatrix();
  16778. return this._absolutePosition;
  16779. };
  16780. /**
  16781. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16782. * Returns the AbstractMesh.
  16783. */
  16784. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16785. if (!absolutePosition) {
  16786. return this;
  16787. }
  16788. var absolutePositionX;
  16789. var absolutePositionY;
  16790. var absolutePositionZ;
  16791. if (absolutePosition.x === undefined) {
  16792. if (arguments.length < 3) {
  16793. return this;
  16794. }
  16795. absolutePositionX = arguments[0];
  16796. absolutePositionY = arguments[1];
  16797. absolutePositionZ = arguments[2];
  16798. }
  16799. else {
  16800. absolutePositionX = absolutePosition.x;
  16801. absolutePositionY = absolutePosition.y;
  16802. absolutePositionZ = absolutePosition.z;
  16803. }
  16804. if (this.parent) {
  16805. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16806. invertParentWorldMatrix.invert();
  16807. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16808. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16809. }
  16810. else {
  16811. this.position.x = absolutePositionX;
  16812. this.position.y = absolutePositionY;
  16813. this.position.z = absolutePositionZ;
  16814. }
  16815. return this;
  16816. };
  16817. /**
  16818. * Sets the mesh position in its local space.
  16819. * Returns the AbstractMesh.
  16820. */
  16821. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16822. this.computeWorldMatrix();
  16823. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16824. return this;
  16825. };
  16826. /**
  16827. * Returns the mesh position in the local space from the current World matrix values.
  16828. * Returns a new Vector3.
  16829. */
  16830. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16831. this.computeWorldMatrix();
  16832. var invLocalWorldMatrix = this._localWorld.clone();
  16833. invLocalWorldMatrix.invert();
  16834. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16835. };
  16836. /**
  16837. * Translates the mesh along the passed Vector3 in its local space.
  16838. * Returns the AbstractMesh.
  16839. */
  16840. TransformNode.prototype.locallyTranslate = function (vector3) {
  16841. this.computeWorldMatrix(true);
  16842. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16843. return this;
  16844. };
  16845. /**
  16846. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16847. * @param targetPoint the position (must be in same space as current mesh) to look at
  16848. * @param yawCor optional yaw (y-axis) correction in radians
  16849. * @param pitchCor optional pitch (x-axis) correction in radians
  16850. * @param rollCor optional roll (z-axis) correction in radians
  16851. * @param space the choosen space of the target
  16852. * @returns the TransformNode.
  16853. */
  16854. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16855. if (yawCor === void 0) { yawCor = 0; }
  16856. if (pitchCor === void 0) { pitchCor = 0; }
  16857. if (rollCor === void 0) { rollCor = 0; }
  16858. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16859. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16860. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16861. targetPoint.subtractToRef(pos, dv);
  16862. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16863. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16864. var pitch = Math.atan2(dv.y, len);
  16865. if (this.rotationQuaternion) {
  16866. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16867. }
  16868. else {
  16869. this.rotation.x = pitch + pitchCor;
  16870. this.rotation.y = yaw + yawCor;
  16871. this.rotation.z = rollCor;
  16872. }
  16873. return this;
  16874. };
  16875. /**
  16876. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16877. * This Vector3 is expressed in the World space.
  16878. */
  16879. TransformNode.prototype.getDirection = function (localAxis) {
  16880. var result = BABYLON.Vector3.Zero();
  16881. this.getDirectionToRef(localAxis, result);
  16882. return result;
  16883. };
  16884. /**
  16885. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16886. * localAxis is expressed in the mesh local space.
  16887. * result is computed in the Wordl space from the mesh World matrix.
  16888. * Returns the AbstractMesh.
  16889. */
  16890. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16891. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16892. return this;
  16893. };
  16894. /**
  16895. * Sets a new pivot point to the current node
  16896. * @param point defines the new pivot point to use
  16897. * @param space defines if the point is in world or local space (local by default)
  16898. * @returns the current TransformNode
  16899. */
  16900. TransformNode.prototype.setPivotPoint = function (point, space) {
  16901. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16902. if (this.getScene().getRenderId() == 0) {
  16903. this.computeWorldMatrix(true);
  16904. }
  16905. var wm = this.getWorldMatrix();
  16906. if (space == BABYLON.Space.WORLD) {
  16907. var tmat = BABYLON.Tmp.Matrix[0];
  16908. wm.invertToRef(tmat);
  16909. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16910. }
  16911. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16912. };
  16913. /**
  16914. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16915. */
  16916. TransformNode.prototype.getPivotPoint = function () {
  16917. var point = BABYLON.Vector3.Zero();
  16918. this.getPivotPointToRef(point);
  16919. return point;
  16920. };
  16921. /**
  16922. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16923. * Returns the AbstractMesh.
  16924. */
  16925. TransformNode.prototype.getPivotPointToRef = function (result) {
  16926. result.x = -this._pivotMatrix.m[12];
  16927. result.y = -this._pivotMatrix.m[13];
  16928. result.z = -this._pivotMatrix.m[14];
  16929. return this;
  16930. };
  16931. /**
  16932. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16933. */
  16934. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16935. var point = BABYLON.Vector3.Zero();
  16936. this.getAbsolutePivotPointToRef(point);
  16937. return point;
  16938. };
  16939. /**
  16940. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16941. * Returns the AbstractMesh.
  16942. */
  16943. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16944. result.x = this._pivotMatrix.m[12];
  16945. result.y = this._pivotMatrix.m[13];
  16946. result.z = this._pivotMatrix.m[14];
  16947. this.getPivotPointToRef(result);
  16948. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16949. return this;
  16950. };
  16951. /**
  16952. * Defines the passed node as the parent of the current node.
  16953. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16954. * Returns the TransformNode.
  16955. */
  16956. TransformNode.prototype.setParent = function (node) {
  16957. if (node === null) {
  16958. var rotation = BABYLON.Tmp.Quaternion[0];
  16959. var position = BABYLON.Tmp.Vector3[0];
  16960. var scale = BABYLON.Tmp.Vector3[1];
  16961. if (this.parent && this.parent.computeWorldMatrix) {
  16962. this.parent.computeWorldMatrix(true);
  16963. }
  16964. this.computeWorldMatrix(true);
  16965. this.getWorldMatrix().decompose(scale, rotation, position);
  16966. if (this.rotationQuaternion) {
  16967. this.rotationQuaternion.copyFrom(rotation);
  16968. }
  16969. else {
  16970. rotation.toEulerAnglesToRef(this.rotation);
  16971. }
  16972. this.scaling.x = scale.x;
  16973. this.scaling.y = scale.y;
  16974. this.scaling.z = scale.z;
  16975. this.position.x = position.x;
  16976. this.position.y = position.y;
  16977. this.position.z = position.z;
  16978. }
  16979. else {
  16980. var rotation = BABYLON.Tmp.Quaternion[0];
  16981. var position = BABYLON.Tmp.Vector3[0];
  16982. var scale = BABYLON.Tmp.Vector3[1];
  16983. var diffMatrix = BABYLON.Tmp.Matrix[0];
  16984. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  16985. this.computeWorldMatrix(true);
  16986. node.computeWorldMatrix(true);
  16987. node.getWorldMatrix().invertToRef(invParentMatrix);
  16988. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  16989. diffMatrix.decompose(scale, rotation, position);
  16990. if (this.rotationQuaternion) {
  16991. this.rotationQuaternion.copyFrom(rotation);
  16992. }
  16993. else {
  16994. rotation.toEulerAnglesToRef(this.rotation);
  16995. }
  16996. this.position.x = position.x;
  16997. this.position.y = position.y;
  16998. this.position.z = position.z;
  16999. this.scaling.x = scale.x;
  17000. this.scaling.y = scale.y;
  17001. this.scaling.z = scale.z;
  17002. }
  17003. this.parent = node;
  17004. return this;
  17005. };
  17006. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  17007. get: function () {
  17008. return this._nonUniformScaling;
  17009. },
  17010. enumerable: true,
  17011. configurable: true
  17012. });
  17013. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  17014. if (this._nonUniformScaling === value) {
  17015. return false;
  17016. }
  17017. this._nonUniformScaling = true;
  17018. return true;
  17019. };
  17020. /**
  17021. * Attach the current TransformNode to another TransformNode associated with a bone
  17022. * @param bone Bone affecting the TransformNode
  17023. * @param affectedTransformNode TransformNode associated with the bone
  17024. */
  17025. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  17026. this._transformToBoneReferal = affectedTransformNode;
  17027. this.parent = bone;
  17028. if (bone.getWorldMatrix().determinant() < 0) {
  17029. this.scalingDeterminant *= -1;
  17030. }
  17031. return this;
  17032. };
  17033. TransformNode.prototype.detachFromBone = function () {
  17034. if (!this.parent) {
  17035. return this;
  17036. }
  17037. if (this.parent.getWorldMatrix().determinant() < 0) {
  17038. this.scalingDeterminant *= -1;
  17039. }
  17040. this._transformToBoneReferal = null;
  17041. this.parent = null;
  17042. return this;
  17043. };
  17044. /**
  17045. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  17046. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17047. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17048. * The passed axis is also normalized.
  17049. * Returns the AbstractMesh.
  17050. */
  17051. TransformNode.prototype.rotate = function (axis, amount, space) {
  17052. axis.normalize();
  17053. if (!this.rotationQuaternion) {
  17054. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17055. this.rotation = BABYLON.Vector3.Zero();
  17056. }
  17057. var rotationQuaternion;
  17058. if (!space || space === BABYLON.Space.LOCAL) {
  17059. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  17060. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  17061. }
  17062. else {
  17063. if (this.parent) {
  17064. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  17065. invertParentWorldMatrix.invert();
  17066. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  17067. }
  17068. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  17069. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17070. }
  17071. return this;
  17072. };
  17073. /**
  17074. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  17075. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17076. * The passed axis is also normalized.
  17077. * Returns the AbstractMesh.
  17078. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  17079. */
  17080. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  17081. axis.normalize();
  17082. if (!this.rotationQuaternion) {
  17083. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17084. this.rotation.copyFromFloats(0, 0, 0);
  17085. }
  17086. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  17087. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  17088. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  17089. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  17090. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  17091. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  17092. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  17093. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  17094. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17095. return this;
  17096. };
  17097. /**
  17098. * Translates the mesh along the axis vector for the passed distance in the given space.
  17099. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17100. * Returns the AbstractMesh.
  17101. */
  17102. TransformNode.prototype.translate = function (axis, distance, space) {
  17103. var displacementVector = axis.scale(distance);
  17104. if (!space || space === BABYLON.Space.LOCAL) {
  17105. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  17106. this.setPositionWithLocalVector(tempV3);
  17107. }
  17108. else {
  17109. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  17110. }
  17111. return this;
  17112. };
  17113. /**
  17114. * Adds a rotation step to the mesh current rotation.
  17115. * x, y, z are Euler angles expressed in radians.
  17116. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  17117. * This means this rotation is made in the mesh local space only.
  17118. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  17119. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  17120. * ```javascript
  17121. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  17122. * ```
  17123. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  17124. * 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.
  17125. * Returns the AbstractMesh.
  17126. */
  17127. TransformNode.prototype.addRotation = function (x, y, z) {
  17128. var rotationQuaternion;
  17129. if (this.rotationQuaternion) {
  17130. rotationQuaternion = this.rotationQuaternion;
  17131. }
  17132. else {
  17133. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  17134. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  17135. }
  17136. var accumulation = BABYLON.Tmp.Quaternion[0];
  17137. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  17138. rotationQuaternion.multiplyInPlace(accumulation);
  17139. if (!this.rotationQuaternion) {
  17140. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  17141. }
  17142. return this;
  17143. };
  17144. /**
  17145. * Computes the mesh World matrix and returns it.
  17146. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  17147. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  17148. * If the parameter `force`is set to `true`, the actual computation is done.
  17149. * Returns the mesh World Matrix.
  17150. */
  17151. TransformNode.prototype.computeWorldMatrix = function (force) {
  17152. if (this._isWorldMatrixFrozen) {
  17153. return this._worldMatrix;
  17154. }
  17155. if (!force && this.isSynchronized(true)) {
  17156. return this._worldMatrix;
  17157. }
  17158. this._cache.position.copyFrom(this.position);
  17159. this._cache.scaling.copyFrom(this.scaling);
  17160. this._cache.pivotMatrixUpdated = false;
  17161. this._cache.billboardMode = this.billboardMode;
  17162. this._currentRenderId = this.getScene().getRenderId();
  17163. this._isDirty = false;
  17164. // Scaling
  17165. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  17166. // Rotation
  17167. //rotate, if quaternion is set and rotation was used
  17168. if (this.rotationQuaternion) {
  17169. var len = this.rotation.length();
  17170. if (len) {
  17171. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  17172. this.rotation.copyFromFloats(0, 0, 0);
  17173. }
  17174. }
  17175. if (this.rotationQuaternion) {
  17176. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  17177. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17178. }
  17179. else {
  17180. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  17181. this._cache.rotation.copyFrom(this.rotation);
  17182. }
  17183. // Translation
  17184. var camera = this.getScene().activeCamera;
  17185. if (this.infiniteDistance && !this.parent && camera) {
  17186. var cameraWorldMatrix = camera.getWorldMatrix();
  17187. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  17188. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  17189. }
  17190. else {
  17191. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  17192. }
  17193. // Composing transformations
  17194. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  17195. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17196. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  17197. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  17198. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  17199. // Need to decompose each rotation here
  17200. var currentPosition = BABYLON.Tmp.Vector3[3];
  17201. if (this.parent && this.parent.getWorldMatrix) {
  17202. if (this._transformToBoneReferal) {
  17203. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17204. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  17205. }
  17206. else {
  17207. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  17208. }
  17209. }
  17210. else {
  17211. currentPosition.copyFrom(this.position);
  17212. }
  17213. currentPosition.subtractInPlace(camera.globalPosition);
  17214. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  17215. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  17216. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  17217. }
  17218. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  17219. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  17220. }
  17221. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  17222. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  17223. }
  17224. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  17225. }
  17226. else {
  17227. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  17228. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  17229. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  17230. }
  17231. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  17232. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17233. }
  17234. // Local world
  17235. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  17236. // Parent
  17237. if (this.parent && this.parent.getWorldMatrix) {
  17238. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  17239. if (this._transformToBoneReferal) {
  17240. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17241. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  17242. }
  17243. else {
  17244. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  17245. }
  17246. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  17247. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  17248. this._worldMatrix.copyFrom(this._localWorld);
  17249. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  17250. }
  17251. else {
  17252. if (this._transformToBoneReferal) {
  17253. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17254. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  17255. }
  17256. else {
  17257. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  17258. }
  17259. }
  17260. this._markSyncedWithParent();
  17261. }
  17262. else {
  17263. this._worldMatrix.copyFrom(this._localWorld);
  17264. }
  17265. // Post multiply inverse of pivotMatrix
  17266. if (this._postMultiplyPivotMatrix) {
  17267. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  17268. }
  17269. // Normal matrix
  17270. if (this.scaling.isNonUniform) {
  17271. this._updateNonUniformScalingState(true);
  17272. }
  17273. else if (this.parent && this.parent._nonUniformScaling) {
  17274. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  17275. }
  17276. else {
  17277. this._updateNonUniformScalingState(false);
  17278. }
  17279. this._afterComputeWorldMatrix();
  17280. // Absolute position
  17281. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  17282. // Callbacks
  17283. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  17284. if (!this._poseMatrix) {
  17285. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  17286. }
  17287. // Cache the determinant
  17288. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  17289. return this._worldMatrix;
  17290. };
  17291. TransformNode.prototype._afterComputeWorldMatrix = function () {
  17292. };
  17293. /**
  17294. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  17295. * @param func: callback function to add
  17296. *
  17297. * Returns the TransformNode.
  17298. */
  17299. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  17300. this.onAfterWorldMatrixUpdateObservable.add(func);
  17301. return this;
  17302. };
  17303. /**
  17304. * Removes a registered callback function.
  17305. * Returns the TransformNode.
  17306. */
  17307. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  17308. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  17309. return this;
  17310. };
  17311. /**
  17312. * Clone the current transform node
  17313. * Returns the new transform node
  17314. * @param name Name of the new clone
  17315. * @param newParent New parent for the clone
  17316. * @param doNotCloneChildren Do not clone children hierarchy
  17317. */
  17318. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17319. var _this = this;
  17320. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  17321. result.name = name;
  17322. result.id = name;
  17323. if (newParent) {
  17324. result.parent = newParent;
  17325. }
  17326. if (!doNotCloneChildren) {
  17327. // Children
  17328. var directDescendants = this.getDescendants(true);
  17329. for (var index = 0; index < directDescendants.length; index++) {
  17330. var child = directDescendants[index];
  17331. if (child.clone) {
  17332. child.clone(name + "." + child.name, result);
  17333. }
  17334. }
  17335. }
  17336. return result;
  17337. };
  17338. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17339. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17340. serializationObject.type = this.getClassName();
  17341. // Parent
  17342. if (this.parent) {
  17343. serializationObject.parentId = this.parent.id;
  17344. }
  17345. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17346. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17347. }
  17348. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17349. serializationObject.isEnabled = this.isEnabled();
  17350. // Parent
  17351. if (this.parent) {
  17352. serializationObject.parentId = this.parent.id;
  17353. }
  17354. return serializationObject;
  17355. };
  17356. // Statics
  17357. /**
  17358. * Returns a new TransformNode object parsed from the source provided.
  17359. * The parameter `parsedMesh` is the source.
  17360. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17361. */
  17362. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17363. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17364. if (BABYLON.Tags) {
  17365. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17366. }
  17367. if (parsedTransformNode.localMatrix) {
  17368. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17369. }
  17370. else if (parsedTransformNode.pivotMatrix) {
  17371. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17372. }
  17373. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17374. // Parent
  17375. if (parsedTransformNode.parentId) {
  17376. transformNode._waitingParentId = parsedTransformNode.parentId;
  17377. }
  17378. return transformNode;
  17379. };
  17380. /**
  17381. * Releases resources associated with this transform node.
  17382. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17383. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17384. */
  17385. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17386. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17387. // Animations
  17388. this.getScene().stopAnimation(this);
  17389. // Remove from scene
  17390. this.getScene().removeTransformNode(this);
  17391. this.onAfterWorldMatrixUpdateObservable.clear();
  17392. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  17393. };
  17394. // Statics
  17395. TransformNode.BILLBOARDMODE_NONE = 0;
  17396. TransformNode.BILLBOARDMODE_X = 1;
  17397. TransformNode.BILLBOARDMODE_Y = 2;
  17398. TransformNode.BILLBOARDMODE_Z = 4;
  17399. TransformNode.BILLBOARDMODE_ALL = 7;
  17400. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17401. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17402. __decorate([
  17403. BABYLON.serializeAsVector3()
  17404. ], TransformNode.prototype, "_rotation", void 0);
  17405. __decorate([
  17406. BABYLON.serializeAsQuaternion()
  17407. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17408. __decorate([
  17409. BABYLON.serializeAsVector3()
  17410. ], TransformNode.prototype, "_scaling", void 0);
  17411. __decorate([
  17412. BABYLON.serialize()
  17413. ], TransformNode.prototype, "billboardMode", void 0);
  17414. __decorate([
  17415. BABYLON.serialize()
  17416. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17417. __decorate([
  17418. BABYLON.serialize()
  17419. ], TransformNode.prototype, "infiniteDistance", void 0);
  17420. __decorate([
  17421. BABYLON.serializeAsVector3()
  17422. ], TransformNode.prototype, "position", void 0);
  17423. return TransformNode;
  17424. }(BABYLON.Node));
  17425. BABYLON.TransformNode = TransformNode;
  17426. })(BABYLON || (BABYLON = {}));
  17427. //# sourceMappingURL=babylon.transformNode.js.map
  17428. var BABYLON;
  17429. (function (BABYLON) {
  17430. var AbstractMesh = /** @class */ (function (_super) {
  17431. __extends(AbstractMesh, _super);
  17432. // Constructor
  17433. function AbstractMesh(name, scene) {
  17434. if (scene === void 0) { scene = null; }
  17435. var _this = _super.call(this, name, scene, false) || this;
  17436. _this._facetNb = 0; // facet number
  17437. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17438. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17439. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17440. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17441. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17442. _this._subDiv = {
  17443. max: 1,
  17444. X: 1,
  17445. Y: 1,
  17446. Z: 1
  17447. };
  17448. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17449. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17450. // Events
  17451. /**
  17452. * An event triggered when this mesh collides with another one
  17453. * @type {BABYLON.Observable}
  17454. */
  17455. _this.onCollideObservable = new BABYLON.Observable();
  17456. /**
  17457. * An event triggered when the collision's position changes
  17458. * @type {BABYLON.Observable}
  17459. */
  17460. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17461. /**
  17462. * An event triggered when material is changed
  17463. * @type {BABYLON.Observable}
  17464. */
  17465. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17466. // Properties
  17467. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17468. /**
  17469. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17470. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17471. * or
  17472. * 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.
  17473. * for more info check WebGl documentations
  17474. */
  17475. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17476. /**
  17477. * 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:
  17478. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17479. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17480. * 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.
  17481. */
  17482. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17483. /**
  17484. * 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.
  17485. * The default value is -1 which means don't break the query and wait till the result.
  17486. */
  17487. _this.occlusionRetryCount = -1;
  17488. _this._occlusionInternalRetryCounter = 0;
  17489. _this._isOccluded = false;
  17490. _this._isOcclusionQueryInProgress = false;
  17491. _this._visibility = 1.0;
  17492. _this.alphaIndex = Number.MAX_VALUE;
  17493. _this.isVisible = true;
  17494. _this.isPickable = true;
  17495. _this.showBoundingBox = false;
  17496. _this.showSubMeshesBoundingBox = false;
  17497. _this.isBlocker = false;
  17498. _this.enablePointerMoveEvents = false;
  17499. _this.renderingGroupId = 0;
  17500. _this._receiveShadows = false;
  17501. _this.renderOutline = false;
  17502. _this.outlineColor = BABYLON.Color3.Red();
  17503. _this.outlineWidth = 0.02;
  17504. _this.renderOverlay = false;
  17505. _this.overlayColor = BABYLON.Color3.Red();
  17506. _this.overlayAlpha = 0.5;
  17507. _this._hasVertexAlpha = false;
  17508. _this._useVertexColors = true;
  17509. _this._computeBonesUsingShaders = true;
  17510. _this._numBoneInfluencers = 4;
  17511. _this._applyFog = true;
  17512. _this.useOctreeForRenderingSelection = true;
  17513. _this.useOctreeForPicking = true;
  17514. _this.useOctreeForCollisions = true;
  17515. _this._layerMask = 0x0FFFFFFF;
  17516. /**
  17517. * True if the mesh must be rendered in any case.
  17518. */
  17519. _this.alwaysSelectAsActiveMesh = false;
  17520. /**
  17521. * This scene's action manager
  17522. * @type {BABYLON.ActionManager}
  17523. */
  17524. _this.actionManager = null;
  17525. // Physics
  17526. _this.physicsImpostor = null;
  17527. // Collisions
  17528. _this._checkCollisions = false;
  17529. _this._collisionMask = -1;
  17530. _this._collisionGroup = -1;
  17531. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17532. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17533. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17534. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17535. // Edges
  17536. _this.edgesWidth = 1;
  17537. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17538. // Cache
  17539. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17540. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17541. _this._renderId = 0;
  17542. _this._intersectionsInProgress = new Array();
  17543. _this._unIndexed = false;
  17544. _this._lightSources = new Array();
  17545. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17546. if (collidedMesh === void 0) { collidedMesh = null; }
  17547. //TODO move this to the collision coordinator!
  17548. if (_this.getScene().workerCollisions)
  17549. newPosition.multiplyInPlace(_this._collider._radius);
  17550. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17551. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17552. _this.position.addInPlace(_this._diffPositionForCollisions);
  17553. }
  17554. if (collidedMesh) {
  17555. _this.onCollideObservable.notifyObservers(collidedMesh);
  17556. }
  17557. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17558. };
  17559. _this.getScene().addMesh(_this);
  17560. _this._resyncLightSources();
  17561. return _this;
  17562. }
  17563. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17564. get: function () {
  17565. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17566. },
  17567. enumerable: true,
  17568. configurable: true
  17569. });
  17570. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17571. get: function () {
  17572. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17573. },
  17574. enumerable: true,
  17575. configurable: true
  17576. });
  17577. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17578. get: function () {
  17579. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17580. },
  17581. enumerable: true,
  17582. configurable: true
  17583. });
  17584. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17585. get: function () {
  17586. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17587. },
  17588. enumerable: true,
  17589. configurable: true
  17590. });
  17591. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17592. get: function () {
  17593. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17594. },
  17595. enumerable: true,
  17596. configurable: true
  17597. });
  17598. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17599. /**
  17600. * Read-only : the number of facets in the mesh
  17601. */
  17602. get: function () {
  17603. return this._facetNb;
  17604. },
  17605. enumerable: true,
  17606. configurable: true
  17607. });
  17608. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17609. /**
  17610. * The number (integer) of subdivisions per axis in the partioning space
  17611. */
  17612. get: function () {
  17613. return this._partitioningSubdivisions;
  17614. },
  17615. set: function (nb) {
  17616. this._partitioningSubdivisions = nb;
  17617. },
  17618. enumerable: true,
  17619. configurable: true
  17620. });
  17621. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17622. /**
  17623. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17624. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17625. */
  17626. get: function () {
  17627. return this._partitioningBBoxRatio;
  17628. },
  17629. set: function (ratio) {
  17630. this._partitioningBBoxRatio = ratio;
  17631. },
  17632. enumerable: true,
  17633. configurable: true
  17634. });
  17635. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17636. /**
  17637. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17638. * Works only for updatable meshes.
  17639. * Doesn't work with multi-materials.
  17640. */
  17641. get: function () {
  17642. return this._facetDepthSort;
  17643. },
  17644. set: function (sort) {
  17645. this._facetDepthSort = sort;
  17646. },
  17647. enumerable: true,
  17648. configurable: true
  17649. });
  17650. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17651. /**
  17652. * The location (Vector3) where the facet depth sort must be computed from.
  17653. * By default, the active camera position.
  17654. * Used only when facet depth sort is enabled.
  17655. */
  17656. get: function () {
  17657. return this._facetDepthSortFrom;
  17658. },
  17659. set: function (location) {
  17660. this._facetDepthSortFrom = location;
  17661. },
  17662. enumerable: true,
  17663. configurable: true
  17664. });
  17665. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17666. /**
  17667. * Read-only boolean : is the feature facetData enabled ?
  17668. */
  17669. get: function () {
  17670. return this._facetDataEnabled;
  17671. },
  17672. enumerable: true,
  17673. configurable: true
  17674. });
  17675. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17676. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17677. return false;
  17678. }
  17679. this._markSubMeshesAsMiscDirty();
  17680. return true;
  17681. };
  17682. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17683. set: function (callback) {
  17684. if (this._onCollideObserver) {
  17685. this.onCollideObservable.remove(this._onCollideObserver);
  17686. }
  17687. this._onCollideObserver = this.onCollideObservable.add(callback);
  17688. },
  17689. enumerable: true,
  17690. configurable: true
  17691. });
  17692. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17693. set: function (callback) {
  17694. if (this._onCollisionPositionChangeObserver) {
  17695. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17696. }
  17697. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17698. },
  17699. enumerable: true,
  17700. configurable: true
  17701. });
  17702. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17703. /**
  17704. * Property isOccluded : 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.
  17705. */
  17706. get: function () {
  17707. return this._isOccluded;
  17708. },
  17709. set: function (value) {
  17710. this._isOccluded = value;
  17711. },
  17712. enumerable: true,
  17713. configurable: true
  17714. });
  17715. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17716. /**
  17717. * Flag to check the progress status of the query
  17718. */
  17719. get: function () {
  17720. return this._isOcclusionQueryInProgress;
  17721. },
  17722. enumerable: true,
  17723. configurable: true
  17724. });
  17725. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17726. /**
  17727. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17728. */
  17729. get: function () {
  17730. return this._visibility;
  17731. },
  17732. /**
  17733. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17734. */
  17735. set: function (value) {
  17736. if (this._visibility === value) {
  17737. return;
  17738. }
  17739. this._visibility = value;
  17740. this._markSubMeshesAsMiscDirty();
  17741. },
  17742. enumerable: true,
  17743. configurable: true
  17744. });
  17745. Object.defineProperty(AbstractMesh.prototype, "material", {
  17746. get: function () {
  17747. return this._material;
  17748. },
  17749. set: function (value) {
  17750. if (this._material === value) {
  17751. return;
  17752. }
  17753. this._material = value;
  17754. if (this.onMaterialChangedObservable.hasObservers) {
  17755. this.onMaterialChangedObservable.notifyObservers(this);
  17756. }
  17757. if (!this.subMeshes) {
  17758. return;
  17759. }
  17760. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17761. var subMesh = _a[_i];
  17762. subMesh.setEffect(null);
  17763. }
  17764. },
  17765. enumerable: true,
  17766. configurable: true
  17767. });
  17768. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17769. get: function () {
  17770. return this._receiveShadows;
  17771. },
  17772. set: function (value) {
  17773. if (this._receiveShadows === value) {
  17774. return;
  17775. }
  17776. this._receiveShadows = value;
  17777. this._markSubMeshesAsLightDirty();
  17778. },
  17779. enumerable: true,
  17780. configurable: true
  17781. });
  17782. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17783. get: function () {
  17784. return this._hasVertexAlpha;
  17785. },
  17786. set: function (value) {
  17787. if (this._hasVertexAlpha === value) {
  17788. return;
  17789. }
  17790. this._hasVertexAlpha = value;
  17791. this._markSubMeshesAsAttributesDirty();
  17792. this._markSubMeshesAsMiscDirty();
  17793. },
  17794. enumerable: true,
  17795. configurable: true
  17796. });
  17797. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17798. get: function () {
  17799. return this._useVertexColors;
  17800. },
  17801. set: function (value) {
  17802. if (this._useVertexColors === value) {
  17803. return;
  17804. }
  17805. this._useVertexColors = value;
  17806. this._markSubMeshesAsAttributesDirty();
  17807. },
  17808. enumerable: true,
  17809. configurable: true
  17810. });
  17811. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17812. get: function () {
  17813. return this._computeBonesUsingShaders;
  17814. },
  17815. set: function (value) {
  17816. if (this._computeBonesUsingShaders === value) {
  17817. return;
  17818. }
  17819. this._computeBonesUsingShaders = value;
  17820. this._markSubMeshesAsAttributesDirty();
  17821. },
  17822. enumerable: true,
  17823. configurable: true
  17824. });
  17825. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17826. get: function () {
  17827. return this._numBoneInfluencers;
  17828. },
  17829. set: function (value) {
  17830. if (this._numBoneInfluencers === value) {
  17831. return;
  17832. }
  17833. this._numBoneInfluencers = value;
  17834. this._markSubMeshesAsAttributesDirty();
  17835. },
  17836. enumerable: true,
  17837. configurable: true
  17838. });
  17839. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17840. get: function () {
  17841. return this._applyFog;
  17842. },
  17843. set: function (value) {
  17844. if (this._applyFog === value) {
  17845. return;
  17846. }
  17847. this._applyFog = value;
  17848. this._markSubMeshesAsMiscDirty();
  17849. },
  17850. enumerable: true,
  17851. configurable: true
  17852. });
  17853. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17854. get: function () {
  17855. return this._layerMask;
  17856. },
  17857. set: function (value) {
  17858. if (value === this._layerMask) {
  17859. return;
  17860. }
  17861. this._layerMask = value;
  17862. this._resyncLightSources();
  17863. },
  17864. enumerable: true,
  17865. configurable: true
  17866. });
  17867. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17868. get: function () {
  17869. return this._collisionMask;
  17870. },
  17871. set: function (mask) {
  17872. this._collisionMask = !isNaN(mask) ? mask : -1;
  17873. },
  17874. enumerable: true,
  17875. configurable: true
  17876. });
  17877. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17878. get: function () {
  17879. return this._collisionGroup;
  17880. },
  17881. set: function (mask) {
  17882. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17883. },
  17884. enumerable: true,
  17885. configurable: true
  17886. });
  17887. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17888. get: function () {
  17889. return null;
  17890. },
  17891. enumerable: true,
  17892. configurable: true
  17893. });
  17894. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17895. get: function () {
  17896. return this._skeleton;
  17897. },
  17898. set: function (value) {
  17899. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17900. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17901. }
  17902. if (value && value.needInitialSkinMatrix) {
  17903. value._registerMeshWithPoseMatrix(this);
  17904. }
  17905. this._skeleton = value;
  17906. if (!this._skeleton) {
  17907. this._bonesTransformMatrices = null;
  17908. }
  17909. this._markSubMeshesAsAttributesDirty();
  17910. },
  17911. enumerable: true,
  17912. configurable: true
  17913. });
  17914. /**
  17915. * Returns the string "AbstractMesh"
  17916. */
  17917. AbstractMesh.prototype.getClassName = function () {
  17918. return "AbstractMesh";
  17919. };
  17920. /**
  17921. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17922. */
  17923. AbstractMesh.prototype.toString = function (fullDetails) {
  17924. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17925. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17926. if (this._skeleton) {
  17927. ret += ", skeleton: " + this._skeleton.name;
  17928. }
  17929. if (fullDetails) {
  17930. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17931. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17932. }
  17933. return ret;
  17934. };
  17935. AbstractMesh.prototype._rebuild = function () {
  17936. if (this._occlusionQuery) {
  17937. this._occlusionQuery = null;
  17938. }
  17939. if (this._edgesRenderer) {
  17940. this._edgesRenderer._rebuild();
  17941. }
  17942. if (!this.subMeshes) {
  17943. return;
  17944. }
  17945. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17946. var subMesh = _a[_i];
  17947. subMesh._rebuild();
  17948. }
  17949. };
  17950. AbstractMesh.prototype._resyncLightSources = function () {
  17951. this._lightSources.length = 0;
  17952. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17953. var light = _a[_i];
  17954. if (!light.isEnabled()) {
  17955. continue;
  17956. }
  17957. if (light.canAffectMesh(this)) {
  17958. this._lightSources.push(light);
  17959. }
  17960. }
  17961. this._markSubMeshesAsLightDirty();
  17962. };
  17963. AbstractMesh.prototype._resyncLighSource = function (light) {
  17964. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17965. var index = this._lightSources.indexOf(light);
  17966. if (index === -1) {
  17967. if (!isIn) {
  17968. return;
  17969. }
  17970. this._lightSources.push(light);
  17971. }
  17972. else {
  17973. if (isIn) {
  17974. return;
  17975. }
  17976. this._lightSources.splice(index, 1);
  17977. }
  17978. this._markSubMeshesAsLightDirty();
  17979. };
  17980. AbstractMesh.prototype._removeLightSource = function (light) {
  17981. var index = this._lightSources.indexOf(light);
  17982. if (index === -1) {
  17983. return;
  17984. }
  17985. this._lightSources.splice(index, 1);
  17986. this._markSubMeshesAsLightDirty();
  17987. };
  17988. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  17989. if (!this.subMeshes) {
  17990. return;
  17991. }
  17992. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17993. var subMesh = _a[_i];
  17994. if (subMesh._materialDefines) {
  17995. func(subMesh._materialDefines);
  17996. }
  17997. }
  17998. };
  17999. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  18000. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  18001. };
  18002. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  18003. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  18004. };
  18005. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  18006. if (!this.subMeshes) {
  18007. return;
  18008. }
  18009. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18010. var subMesh = _a[_i];
  18011. var material = subMesh.getMaterial();
  18012. if (material) {
  18013. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  18014. }
  18015. }
  18016. };
  18017. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  18018. /**
  18019. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18020. * Default : (1.0, 1.0, 1.0)
  18021. */
  18022. get: function () {
  18023. return this._scaling;
  18024. },
  18025. /**
  18026. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18027. * Default : (1.0, 1.0, 1.0)
  18028. */
  18029. set: function (newScaling) {
  18030. this._scaling = newScaling;
  18031. if (this.physicsImpostor) {
  18032. this.physicsImpostor.forceUpdate();
  18033. }
  18034. },
  18035. enumerable: true,
  18036. configurable: true
  18037. });
  18038. // Methods
  18039. /**
  18040. * Disables the mesh edger rendering mode.
  18041. * Returns the AbstractMesh.
  18042. */
  18043. AbstractMesh.prototype.disableEdgesRendering = function () {
  18044. if (this._edgesRenderer) {
  18045. this._edgesRenderer.dispose();
  18046. this._edgesRenderer = null;
  18047. }
  18048. return this;
  18049. };
  18050. /**
  18051. * Enables the edge rendering mode on the mesh.
  18052. * This mode makes the mesh edges visible.
  18053. * Returns the AbstractMesh.
  18054. */
  18055. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  18056. if (epsilon === void 0) { epsilon = 0.95; }
  18057. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  18058. this.disableEdgesRendering();
  18059. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  18060. return this;
  18061. };
  18062. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  18063. /**
  18064. * Returns true if the mesh is blocked. Used by the class Mesh.
  18065. * Returns the boolean `false` by default.
  18066. */
  18067. get: function () {
  18068. return false;
  18069. },
  18070. enumerable: true,
  18071. configurable: true
  18072. });
  18073. /**
  18074. * Returns the mesh itself by default, used by the class Mesh.
  18075. * Returned type : AbstractMesh
  18076. */
  18077. AbstractMesh.prototype.getLOD = function (camera) {
  18078. return this;
  18079. };
  18080. /**
  18081. * Returns 0 by default, used by the class Mesh.
  18082. * Returns an integer.
  18083. */
  18084. AbstractMesh.prototype.getTotalVertices = function () {
  18085. return 0;
  18086. };
  18087. /**
  18088. * Returns null by default, used by the class Mesh.
  18089. * Returned type : integer array
  18090. */
  18091. AbstractMesh.prototype.getIndices = function () {
  18092. return null;
  18093. };
  18094. /**
  18095. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  18096. * Returned type : float array or Float32Array
  18097. */
  18098. AbstractMesh.prototype.getVerticesData = function (kind) {
  18099. return null;
  18100. };
  18101. /**
  18102. * Sets the vertex data of the mesh geometry for the requested `kind`.
  18103. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  18104. * The `data` are either a numeric array either a Float32Array.
  18105. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  18106. * 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).
  18107. * Note that a new underlying VertexBuffer object is created each call.
  18108. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  18109. *
  18110. * Possible `kind` values :
  18111. * - BABYLON.VertexBuffer.PositionKind
  18112. * - BABYLON.VertexBuffer.UVKind
  18113. * - BABYLON.VertexBuffer.UV2Kind
  18114. * - BABYLON.VertexBuffer.UV3Kind
  18115. * - BABYLON.VertexBuffer.UV4Kind
  18116. * - BABYLON.VertexBuffer.UV5Kind
  18117. * - BABYLON.VertexBuffer.UV6Kind
  18118. * - BABYLON.VertexBuffer.ColorKind
  18119. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18120. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18121. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18122. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18123. *
  18124. * Returns the Mesh.
  18125. */
  18126. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  18127. return this;
  18128. };
  18129. /**
  18130. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  18131. * If the mesh has no geometry, it is simply returned as it is.
  18132. * The `data` are either a numeric array either a Float32Array.
  18133. * No new underlying VertexBuffer object is created.
  18134. * 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.
  18135. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  18136. *
  18137. * Possible `kind` values :
  18138. * - BABYLON.VertexBuffer.PositionKind
  18139. * - BABYLON.VertexBuffer.UVKind
  18140. * - BABYLON.VertexBuffer.UV2Kind
  18141. * - BABYLON.VertexBuffer.UV3Kind
  18142. * - BABYLON.VertexBuffer.UV4Kind
  18143. * - BABYLON.VertexBuffer.UV5Kind
  18144. * - BABYLON.VertexBuffer.UV6Kind
  18145. * - BABYLON.VertexBuffer.ColorKind
  18146. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18147. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18148. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18149. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18150. *
  18151. * Returns the Mesh.
  18152. */
  18153. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  18154. return this;
  18155. };
  18156. /**
  18157. * Sets the mesh indices.
  18158. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  18159. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  18160. * This method creates a new index buffer each call.
  18161. * Returns the Mesh.
  18162. */
  18163. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  18164. return this;
  18165. };
  18166. /** Returns false by default, used by the class Mesh.
  18167. * Returns a boolean
  18168. */
  18169. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  18170. return false;
  18171. };
  18172. /**
  18173. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  18174. * Returns a BoundingInfo
  18175. */
  18176. AbstractMesh.prototype.getBoundingInfo = function () {
  18177. if (this._masterMesh) {
  18178. return this._masterMesh.getBoundingInfo();
  18179. }
  18180. if (!this._boundingInfo) {
  18181. // this._boundingInfo is being created here
  18182. this._updateBoundingInfo();
  18183. }
  18184. // cannot be null.
  18185. return this._boundingInfo;
  18186. };
  18187. /**
  18188. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  18189. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  18190. */
  18191. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  18192. if (includeDescendants === void 0) { includeDescendants = true; }
  18193. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  18194. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  18195. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  18196. if (maxDimension === 0) {
  18197. return this;
  18198. }
  18199. var scale = 1 / maxDimension;
  18200. this.scaling.scaleInPlace(scale);
  18201. return this;
  18202. };
  18203. /**
  18204. * Sets a mesh new object BoundingInfo.
  18205. * Returns the AbstractMesh.
  18206. */
  18207. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  18208. this._boundingInfo = boundingInfo;
  18209. return this;
  18210. };
  18211. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  18212. get: function () {
  18213. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  18214. },
  18215. enumerable: true,
  18216. configurable: true
  18217. });
  18218. AbstractMesh.prototype._preActivate = function () {
  18219. };
  18220. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18221. };
  18222. AbstractMesh.prototype._activate = function (renderId) {
  18223. this._renderId = renderId;
  18224. };
  18225. /**
  18226. * Returns the latest update of the World matrix
  18227. * Returns a Matrix.
  18228. */
  18229. AbstractMesh.prototype.getWorldMatrix = function () {
  18230. if (this._masterMesh) {
  18231. return this._masterMesh.getWorldMatrix();
  18232. }
  18233. return _super.prototype.getWorldMatrix.call(this);
  18234. };
  18235. /**
  18236. * Returns the latest update of the World matrix determinant.
  18237. */
  18238. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  18239. if (this._masterMesh) {
  18240. return this._masterMesh._getWorldMatrixDeterminant();
  18241. }
  18242. return _super.prototype._getWorldMatrixDeterminant.call(this);
  18243. };
  18244. // ================================== Point of View Movement =================================
  18245. /**
  18246. * Perform relative position change from the point of view of behind the front of the mesh.
  18247. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18248. * Supports definition of mesh facing forward or backward.
  18249. * @param {number} amountRight
  18250. * @param {number} amountUp
  18251. * @param {number} amountForward
  18252. *
  18253. * Returns the AbstractMesh.
  18254. */
  18255. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  18256. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  18257. return this;
  18258. };
  18259. /**
  18260. * Calculate relative position change from the point of view of behind the front of the mesh.
  18261. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18262. * Supports definition of mesh facing forward or backward.
  18263. * @param {number} amountRight
  18264. * @param {number} amountUp
  18265. * @param {number} amountForward
  18266. *
  18267. * Returns a new Vector3.
  18268. */
  18269. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  18270. var rotMatrix = new BABYLON.Matrix();
  18271. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18272. rotQuaternion.toRotationMatrix(rotMatrix);
  18273. var translationDelta = BABYLON.Vector3.Zero();
  18274. var defForwardMult = this.definedFacingForward ? -1 : 1;
  18275. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  18276. return translationDelta;
  18277. };
  18278. // ================================== Point of View Rotation =================================
  18279. /**
  18280. * Perform relative rotation change from the point of view of behind the front of the mesh.
  18281. * Supports definition of mesh facing forward or backward.
  18282. * @param {number} flipBack
  18283. * @param {number} twirlClockwise
  18284. * @param {number} tiltRight
  18285. *
  18286. * Returns the AbstractMesh.
  18287. */
  18288. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18289. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  18290. return this;
  18291. };
  18292. /**
  18293. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  18294. * Supports definition of mesh facing forward or backward.
  18295. * @param {number} flipBack
  18296. * @param {number} twirlClockwise
  18297. * @param {number} tiltRight
  18298. *
  18299. * Returns a new Vector3.
  18300. */
  18301. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18302. var defForwardMult = this.definedFacingForward ? 1 : -1;
  18303. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  18304. };
  18305. /**
  18306. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  18307. * @param includeDescendants Include bounding info from descendants as well (true by default).
  18308. */
  18309. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  18310. if (includeDescendants === void 0) { includeDescendants = true; }
  18311. this.computeWorldMatrix(true);
  18312. var min;
  18313. var max;
  18314. var boundingInfo = this.getBoundingInfo();
  18315. if (!this.subMeshes) {
  18316. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18317. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18318. }
  18319. else {
  18320. min = boundingInfo.boundingBox.minimumWorld;
  18321. max = boundingInfo.boundingBox.maximumWorld;
  18322. }
  18323. if (includeDescendants) {
  18324. var descendants = this.getDescendants(false);
  18325. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18326. var descendant = descendants_1[_i];
  18327. var childMesh = descendant;
  18328. childMesh.computeWorldMatrix(true);
  18329. //make sure we have the needed params to get mix and max
  18330. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18331. continue;
  18332. }
  18333. var childBoundingInfo = childMesh.getBoundingInfo();
  18334. var boundingBox = childBoundingInfo.boundingBox;
  18335. var minBox = boundingBox.minimumWorld;
  18336. var maxBox = boundingBox.maximumWorld;
  18337. BABYLON.Tools.CheckExtends(minBox, min, max);
  18338. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18339. }
  18340. }
  18341. return {
  18342. min: min,
  18343. max: max
  18344. };
  18345. };
  18346. /**
  18347. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18348. * Returns the AbstractMesh.
  18349. */
  18350. AbstractMesh.prototype._updateBoundingInfo = function () {
  18351. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18352. this._boundingInfo.update(this.worldMatrixFromCache);
  18353. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18354. return this;
  18355. };
  18356. /**
  18357. * Update a mesh's children BoundingInfo objects only.
  18358. * Returns the AbstractMesh.
  18359. */
  18360. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18361. if (!this.subMeshes) {
  18362. return this;
  18363. }
  18364. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18365. var subMesh = this.subMeshes[subIndex];
  18366. if (!subMesh.IsGlobal) {
  18367. subMesh.updateBoundingInfo(matrix);
  18368. }
  18369. }
  18370. return this;
  18371. };
  18372. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18373. // Bounding info
  18374. this._updateBoundingInfo();
  18375. };
  18376. /**
  18377. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18378. * A mesh is in the frustum if its bounding box intersects the frustum.
  18379. * Boolean returned.
  18380. */
  18381. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18382. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18383. };
  18384. /**
  18385. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18386. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18387. * Boolean returned.
  18388. */
  18389. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18390. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18391. ;
  18392. };
  18393. /**
  18394. * True if the mesh intersects another mesh or a SolidParticle object.
  18395. * 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)
  18396. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18397. * Returns a boolean.
  18398. */
  18399. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18400. if (precise === void 0) { precise = false; }
  18401. if (!this._boundingInfo || !mesh._boundingInfo) {
  18402. return false;
  18403. }
  18404. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18405. return true;
  18406. }
  18407. if (includeDescendants) {
  18408. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18409. var child = _a[_i];
  18410. if (child.intersectsMesh(mesh, precise, true)) {
  18411. return true;
  18412. }
  18413. }
  18414. }
  18415. return false;
  18416. };
  18417. /**
  18418. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18419. * Returns a boolean.
  18420. */
  18421. AbstractMesh.prototype.intersectsPoint = function (point) {
  18422. if (!this._boundingInfo) {
  18423. return false;
  18424. }
  18425. return this._boundingInfo.intersectsPoint(point);
  18426. };
  18427. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18428. return this.physicsImpostor;
  18429. };
  18430. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18431. if (camera === void 0) { camera = null; }
  18432. if (!camera) {
  18433. camera = this.getScene().activeCamera;
  18434. }
  18435. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18436. };
  18437. /**
  18438. * Returns the distance from the mesh to the active camera.
  18439. * Returns a float.
  18440. */
  18441. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18442. if (camera === void 0) { camera = null; }
  18443. if (!camera) {
  18444. camera = this.getScene().activeCamera;
  18445. }
  18446. return this.absolutePosition.subtract(camera.position).length();
  18447. };
  18448. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18449. if (!this.physicsImpostor) {
  18450. return this;
  18451. }
  18452. this.physicsImpostor.applyImpulse(force, contactPoint);
  18453. return this;
  18454. };
  18455. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18456. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18457. return this;
  18458. }
  18459. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18460. mainPivot: pivot1,
  18461. connectedPivot: pivot2,
  18462. nativeParams: options
  18463. });
  18464. return this;
  18465. };
  18466. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18467. // Collisions
  18468. /**
  18469. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18470. * Default `false`.
  18471. */
  18472. get: function () {
  18473. return this._checkCollisions;
  18474. },
  18475. set: function (collisionEnabled) {
  18476. this._checkCollisions = collisionEnabled;
  18477. if (this.getScene().workerCollisions) {
  18478. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18479. }
  18480. },
  18481. enumerable: true,
  18482. configurable: true
  18483. });
  18484. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18485. /**
  18486. * Gets Collider object used to compute collisions (not physics)
  18487. */
  18488. get: function () {
  18489. return this._collider;
  18490. },
  18491. enumerable: true,
  18492. configurable: true
  18493. });
  18494. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18495. var globalPosition = this.getAbsolutePosition();
  18496. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18497. if (!this._collider) {
  18498. this._collider = new BABYLON.Collider();
  18499. }
  18500. this._collider._radius = this.ellipsoid;
  18501. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18502. return this;
  18503. };
  18504. // Submeshes octree
  18505. /**
  18506. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18507. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18508. * Returns an Octree of submeshes.
  18509. */
  18510. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18511. if (maxCapacity === void 0) { maxCapacity = 64; }
  18512. if (maxDepth === void 0) { maxDepth = 2; }
  18513. if (!this._submeshesOctree) {
  18514. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18515. }
  18516. this.computeWorldMatrix(true);
  18517. var boundingInfo = this.getBoundingInfo();
  18518. // Update octree
  18519. var bbox = boundingInfo.boundingBox;
  18520. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18521. return this._submeshesOctree;
  18522. };
  18523. // Collisions
  18524. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18525. this._generatePointsArray();
  18526. if (!this._positions) {
  18527. return this;
  18528. }
  18529. // Transformation
  18530. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18531. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18532. subMesh._lastColliderWorldVertices = [];
  18533. subMesh._trianglePlanes = [];
  18534. var start = subMesh.verticesStart;
  18535. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18536. for (var i = start; i < end; i++) {
  18537. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18538. }
  18539. }
  18540. // Collide
  18541. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18542. if (collider.collisionFound) {
  18543. collider.collidedMesh = this;
  18544. }
  18545. return this;
  18546. };
  18547. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18548. var subMeshes;
  18549. var len;
  18550. // Octrees
  18551. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18552. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18553. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18554. len = intersections.length;
  18555. subMeshes = intersections.data;
  18556. }
  18557. else {
  18558. subMeshes = this.subMeshes;
  18559. len = subMeshes.length;
  18560. }
  18561. for (var index = 0; index < len; index++) {
  18562. var subMesh = subMeshes[index];
  18563. // Bounding test
  18564. if (len > 1 && !subMesh._checkCollision(collider))
  18565. continue;
  18566. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18567. }
  18568. return this;
  18569. };
  18570. AbstractMesh.prototype._checkCollision = function (collider) {
  18571. // Bounding box test
  18572. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18573. return this;
  18574. // Transformation matrix
  18575. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18576. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18577. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18578. return this;
  18579. };
  18580. // Picking
  18581. AbstractMesh.prototype._generatePointsArray = function () {
  18582. return false;
  18583. };
  18584. /**
  18585. * Checks if the passed Ray intersects with the mesh.
  18586. * Returns an object PickingInfo.
  18587. */
  18588. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18589. var pickingInfo = new BABYLON.PickingInfo();
  18590. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18591. return pickingInfo;
  18592. }
  18593. if (!this._generatePointsArray()) {
  18594. return pickingInfo;
  18595. }
  18596. var intersectInfo = null;
  18597. // Octrees
  18598. var subMeshes;
  18599. var len;
  18600. if (this._submeshesOctree && this.useOctreeForPicking) {
  18601. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18602. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18603. len = intersections.length;
  18604. subMeshes = intersections.data;
  18605. }
  18606. else {
  18607. subMeshes = this.subMeshes;
  18608. len = subMeshes.length;
  18609. }
  18610. for (var index = 0; index < len; index++) {
  18611. var subMesh = subMeshes[index];
  18612. // Bounding test
  18613. if (len > 1 && !subMesh.canIntersects(ray))
  18614. continue;
  18615. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18616. if (currentIntersectInfo) {
  18617. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18618. intersectInfo = currentIntersectInfo;
  18619. intersectInfo.subMeshId = index;
  18620. if (fastCheck) {
  18621. break;
  18622. }
  18623. }
  18624. }
  18625. }
  18626. if (intersectInfo) {
  18627. // Get picked point
  18628. var world = this.getWorldMatrix();
  18629. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18630. var direction = ray.direction.clone();
  18631. direction = direction.scale(intersectInfo.distance);
  18632. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18633. var pickedPoint = worldOrigin.add(worldDirection);
  18634. // Return result
  18635. pickingInfo.hit = true;
  18636. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18637. pickingInfo.pickedPoint = pickedPoint;
  18638. pickingInfo.pickedMesh = this;
  18639. pickingInfo.bu = intersectInfo.bu || 0;
  18640. pickingInfo.bv = intersectInfo.bv || 0;
  18641. pickingInfo.faceId = intersectInfo.faceId;
  18642. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18643. return pickingInfo;
  18644. }
  18645. return pickingInfo;
  18646. };
  18647. /**
  18648. * Clones the mesh, used by the class Mesh.
  18649. * Just returns `null` for an AbstractMesh.
  18650. */
  18651. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18652. return null;
  18653. };
  18654. /**
  18655. * Disposes all the mesh submeshes.
  18656. * Returns the AbstractMesh.
  18657. */
  18658. AbstractMesh.prototype.releaseSubMeshes = function () {
  18659. if (this.subMeshes) {
  18660. while (this.subMeshes.length) {
  18661. this.subMeshes[0].dispose();
  18662. }
  18663. }
  18664. else {
  18665. this.subMeshes = new Array();
  18666. }
  18667. return this;
  18668. };
  18669. /**
  18670. * Releases resources associated with this abstract mesh.
  18671. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18672. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18673. */
  18674. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18675. var _this = this;
  18676. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18677. var index;
  18678. // Smart Array Retainers.
  18679. this.getScene().freeActiveMeshes();
  18680. this.getScene().freeRenderingGroups();
  18681. // Action manager
  18682. if (this.actionManager !== undefined && this.actionManager !== null) {
  18683. this.actionManager.dispose();
  18684. this.actionManager = null;
  18685. }
  18686. // Skeleton
  18687. this.skeleton = null;
  18688. // Physics
  18689. if (this.physicsImpostor) {
  18690. this.physicsImpostor.dispose();
  18691. }
  18692. // Intersections in progress
  18693. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18694. var other = this._intersectionsInProgress[index];
  18695. var pos = other._intersectionsInProgress.indexOf(this);
  18696. other._intersectionsInProgress.splice(pos, 1);
  18697. }
  18698. this._intersectionsInProgress = [];
  18699. // Lights
  18700. var lights = this.getScene().lights;
  18701. lights.forEach(function (light) {
  18702. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18703. if (meshIndex !== -1) {
  18704. light.includedOnlyMeshes.splice(meshIndex, 1);
  18705. }
  18706. meshIndex = light.excludedMeshes.indexOf(_this);
  18707. if (meshIndex !== -1) {
  18708. light.excludedMeshes.splice(meshIndex, 1);
  18709. }
  18710. // Shadow generators
  18711. var generator = light.getShadowGenerator();
  18712. if (generator) {
  18713. var shadowMap = generator.getShadowMap();
  18714. if (shadowMap && shadowMap.renderList) {
  18715. meshIndex = shadowMap.renderList.indexOf(_this);
  18716. if (meshIndex !== -1) {
  18717. shadowMap.renderList.splice(meshIndex, 1);
  18718. }
  18719. }
  18720. }
  18721. });
  18722. // Edges
  18723. if (this._edgesRenderer) {
  18724. this._edgesRenderer.dispose();
  18725. this._edgesRenderer = null;
  18726. }
  18727. // SubMeshes
  18728. if (this.getClassName() !== "InstancedMesh") {
  18729. this.releaseSubMeshes();
  18730. }
  18731. // Octree
  18732. var sceneOctree = this.getScene().selectionOctree;
  18733. if (sceneOctree !== undefined && sceneOctree !== null) {
  18734. var index = sceneOctree.dynamicContent.indexOf(this);
  18735. if (index !== -1) {
  18736. sceneOctree.dynamicContent.splice(index, 1);
  18737. }
  18738. }
  18739. // Query
  18740. var engine = this.getScene().getEngine();
  18741. if (this._occlusionQuery) {
  18742. this._isOcclusionQueryInProgress = false;
  18743. engine.deleteQuery(this._occlusionQuery);
  18744. this._occlusionQuery = null;
  18745. }
  18746. // Engine
  18747. engine.wipeCaches();
  18748. // Remove from scene
  18749. this.getScene().removeMesh(this);
  18750. if (disposeMaterialAndTextures) {
  18751. if (this.material) {
  18752. this.material.dispose(false, true);
  18753. }
  18754. }
  18755. if (!doNotRecurse) {
  18756. // Particles
  18757. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18758. if (this.getScene().particleSystems[index].emitter === this) {
  18759. this.getScene().particleSystems[index].dispose();
  18760. index--;
  18761. }
  18762. }
  18763. }
  18764. // facet data
  18765. if (this._facetDataEnabled) {
  18766. this.disableFacetData();
  18767. }
  18768. this.onAfterWorldMatrixUpdateObservable.clear();
  18769. this.onCollideObservable.clear();
  18770. this.onCollisionPositionChangeObservable.clear();
  18771. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18772. };
  18773. /**
  18774. * Adds the passed mesh as a child to the current mesh.
  18775. * Returns the AbstractMesh.
  18776. */
  18777. AbstractMesh.prototype.addChild = function (mesh) {
  18778. mesh.setParent(this);
  18779. return this;
  18780. };
  18781. /**
  18782. * Removes the passed mesh from the current mesh children list.
  18783. * Returns the AbstractMesh.
  18784. */
  18785. AbstractMesh.prototype.removeChild = function (mesh) {
  18786. mesh.setParent(null);
  18787. return this;
  18788. };
  18789. // Facet data
  18790. /**
  18791. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18792. * Returns the AbstractMesh.
  18793. */
  18794. AbstractMesh.prototype._initFacetData = function () {
  18795. if (!this._facetNormals) {
  18796. this._facetNormals = new Array();
  18797. }
  18798. if (!this._facetPositions) {
  18799. this._facetPositions = new Array();
  18800. }
  18801. if (!this._facetPartitioning) {
  18802. this._facetPartitioning = new Array();
  18803. }
  18804. this._facetNb = (this.getIndices().length / 3) | 0;
  18805. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18806. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18807. for (var f = 0; f < this._facetNb; f++) {
  18808. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18809. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18810. }
  18811. this._facetDataEnabled = true;
  18812. return this;
  18813. };
  18814. /**
  18815. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18816. * This method can be called within the render loop.
  18817. * 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.
  18818. * Returns the AbstractMesh.
  18819. */
  18820. AbstractMesh.prototype.updateFacetData = function () {
  18821. if (!this._facetDataEnabled) {
  18822. this._initFacetData();
  18823. }
  18824. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18825. var indices = this.getIndices();
  18826. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18827. var bInfo = this.getBoundingInfo();
  18828. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18829. // init arrays, matrix and sort function on first call
  18830. this._facetDepthSortEnabled = true;
  18831. if (indices instanceof Uint16Array) {
  18832. this._depthSortedIndices = new Uint16Array(indices);
  18833. }
  18834. else if (indices instanceof Uint32Array) {
  18835. this._depthSortedIndices = new Uint32Array(indices);
  18836. }
  18837. else {
  18838. var needs32bits = false;
  18839. for (var i = 0; i < indices.length; i++) {
  18840. if (indices[i] > 65535) {
  18841. needs32bits = true;
  18842. break;
  18843. }
  18844. }
  18845. if (needs32bits) {
  18846. this._depthSortedIndices = new Uint32Array(indices);
  18847. }
  18848. else {
  18849. this._depthSortedIndices = new Uint16Array(indices);
  18850. }
  18851. }
  18852. this._facetDepthSortFunction = function (f1, f2) {
  18853. return (f2.sqDistance - f1.sqDistance);
  18854. };
  18855. if (!this._facetDepthSortFrom) {
  18856. var camera = this.getScene().activeCamera;
  18857. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18858. }
  18859. this._depthSortedFacets = [];
  18860. for (var f = 0; f < this._facetNb; f++) {
  18861. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18862. this._depthSortedFacets.push(depthSortedFacet);
  18863. }
  18864. this._invertedMatrix = BABYLON.Matrix.Identity();
  18865. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18866. }
  18867. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18868. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18869. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18870. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18871. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18872. this._subDiv.max = this._partitioningSubdivisions;
  18873. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18874. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18875. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18876. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18877. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18878. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18879. // set the parameters for ComputeNormals()
  18880. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18881. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18882. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18883. this._facetParameters.bInfo = bInfo;
  18884. this._facetParameters.bbSize = this._bbSize;
  18885. this._facetParameters.subDiv = this._subDiv;
  18886. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18887. this._facetParameters.depthSort = this._facetDepthSort;
  18888. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18889. this.computeWorldMatrix(true);
  18890. this._worldMatrix.invertToRef(this._invertedMatrix);
  18891. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18892. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18893. }
  18894. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18895. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18896. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18897. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18898. var l = (this._depthSortedIndices.length / 3) | 0;
  18899. for (var f = 0; f < l; f++) {
  18900. var sind = this._depthSortedFacets[f].ind;
  18901. this._depthSortedIndices[f * 3] = indices[sind];
  18902. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18903. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18904. }
  18905. this.updateIndices(this._depthSortedIndices);
  18906. }
  18907. return this;
  18908. };
  18909. /**
  18910. * Returns the facetLocalNormals array.
  18911. * The normals are expressed in the mesh local space.
  18912. */
  18913. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18914. if (!this._facetNormals) {
  18915. this.updateFacetData();
  18916. }
  18917. return this._facetNormals;
  18918. };
  18919. /**
  18920. * Returns the facetLocalPositions array.
  18921. * The facet positions are expressed in the mesh local space.
  18922. */
  18923. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18924. if (!this._facetPositions) {
  18925. this.updateFacetData();
  18926. }
  18927. return this._facetPositions;
  18928. };
  18929. /**
  18930. * Returns the facetLocalPartioning array.
  18931. */
  18932. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18933. if (!this._facetPartitioning) {
  18934. this.updateFacetData();
  18935. }
  18936. return this._facetPartitioning;
  18937. };
  18938. /**
  18939. * Returns the i-th facet position in the world system.
  18940. * This method allocates a new Vector3 per call.
  18941. */
  18942. AbstractMesh.prototype.getFacetPosition = function (i) {
  18943. var pos = BABYLON.Vector3.Zero();
  18944. this.getFacetPositionToRef(i, pos);
  18945. return pos;
  18946. };
  18947. /**
  18948. * Sets the reference Vector3 with the i-th facet position in the world system.
  18949. * Returns the AbstractMesh.
  18950. */
  18951. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18952. var localPos = (this.getFacetLocalPositions())[i];
  18953. var world = this.getWorldMatrix();
  18954. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18955. return this;
  18956. };
  18957. /**
  18958. * Returns the i-th facet normal in the world system.
  18959. * This method allocates a new Vector3 per call.
  18960. */
  18961. AbstractMesh.prototype.getFacetNormal = function (i) {
  18962. var norm = BABYLON.Vector3.Zero();
  18963. this.getFacetNormalToRef(i, norm);
  18964. return norm;
  18965. };
  18966. /**
  18967. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18968. * Returns the AbstractMesh.
  18969. */
  18970. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18971. var localNorm = (this.getFacetLocalNormals())[i];
  18972. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18973. return this;
  18974. };
  18975. /**
  18976. * 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).
  18977. */
  18978. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18979. var bInfo = this.getBoundingInfo();
  18980. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18981. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18982. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  18983. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  18984. return null;
  18985. }
  18986. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  18987. };
  18988. /**
  18989. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  18990. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  18991. * If checkFace is 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.
  18992. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18993. * 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.
  18994. */
  18995. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  18996. if (checkFace === void 0) { checkFace = false; }
  18997. if (facing === void 0) { facing = true; }
  18998. var world = this.getWorldMatrix();
  18999. var invMat = BABYLON.Tmp.Matrix[5];
  19000. world.invertToRef(invMat);
  19001. var invVect = BABYLON.Tmp.Vector3[8];
  19002. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  19003. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  19004. if (projected) {
  19005. // tranform the local computed projected vector to world coordinates
  19006. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  19007. }
  19008. return closest;
  19009. };
  19010. /**
  19011. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  19012. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  19013. * If checkFace is 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.
  19014. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19015. * 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.
  19016. */
  19017. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  19018. if (checkFace === void 0) { checkFace = false; }
  19019. if (facing === void 0) { facing = true; }
  19020. var closest = null;
  19021. var tmpx = 0.0;
  19022. var tmpy = 0.0;
  19023. var tmpz = 0.0;
  19024. var d = 0.0; // tmp dot facet normal * facet position
  19025. var t0 = 0.0;
  19026. var projx = 0.0;
  19027. var projy = 0.0;
  19028. var projz = 0.0;
  19029. // Get all the facets in the same partitioning block than (x, y, z)
  19030. var facetPositions = this.getFacetLocalPositions();
  19031. var facetNormals = this.getFacetLocalNormals();
  19032. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  19033. if (!facetsInBlock) {
  19034. return null;
  19035. }
  19036. // Get the closest facet to (x, y, z)
  19037. var shortest = Number.MAX_VALUE; // init distance vars
  19038. var tmpDistance = shortest;
  19039. var fib; // current facet in the block
  19040. var norm; // current facet normal
  19041. var p0; // current facet barycenter position
  19042. // loop on all the facets in the current partitioning block
  19043. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  19044. fib = facetsInBlock[idx];
  19045. norm = facetNormals[fib];
  19046. p0 = facetPositions[fib];
  19047. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  19048. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  19049. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  19050. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  19051. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  19052. projx = x + norm.x * t0;
  19053. projy = y + norm.y * t0;
  19054. projz = z + norm.z * t0;
  19055. tmpx = projx - x;
  19056. tmpy = projy - y;
  19057. tmpz = projz - z;
  19058. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  19059. if (tmpDistance < shortest) {
  19060. shortest = tmpDistance;
  19061. closest = fib;
  19062. if (projected) {
  19063. projected.x = projx;
  19064. projected.y = projy;
  19065. projected.z = projz;
  19066. }
  19067. }
  19068. }
  19069. }
  19070. return closest;
  19071. };
  19072. /**
  19073. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  19074. */
  19075. AbstractMesh.prototype.getFacetDataParameters = function () {
  19076. return this._facetParameters;
  19077. };
  19078. /**
  19079. * Disables the feature FacetData and frees the related memory.
  19080. * Returns the AbstractMesh.
  19081. */
  19082. AbstractMesh.prototype.disableFacetData = function () {
  19083. if (this._facetDataEnabled) {
  19084. this._facetDataEnabled = false;
  19085. this._facetPositions = new Array();
  19086. this._facetNormals = new Array();
  19087. this._facetPartitioning = new Array();
  19088. this._facetParameters = null;
  19089. this._depthSortedIndices = new Uint32Array(0);
  19090. }
  19091. return this;
  19092. };
  19093. /**
  19094. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  19095. * Returns the mesh.
  19096. */
  19097. AbstractMesh.prototype.updateIndices = function (indices) {
  19098. return this;
  19099. };
  19100. /**
  19101. * The mesh Geometry. Actually used by the Mesh object.
  19102. * Returns a blank geometry object.
  19103. */
  19104. /**
  19105. * Creates new normals data for the mesh.
  19106. * @param updatable.
  19107. */
  19108. AbstractMesh.prototype.createNormals = function (updatable) {
  19109. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19110. var indices = this.getIndices();
  19111. var normals;
  19112. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19113. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19114. }
  19115. else {
  19116. normals = [];
  19117. }
  19118. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  19119. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  19120. };
  19121. /**
  19122. * Align the mesh with a normal.
  19123. * Returns the mesh.
  19124. */
  19125. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  19126. if (!upDirection) {
  19127. upDirection = BABYLON.Axis.Y;
  19128. }
  19129. var axisX = BABYLON.Tmp.Vector3[0];
  19130. var axisZ = BABYLON.Tmp.Vector3[1];
  19131. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  19132. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  19133. if (this.rotationQuaternion) {
  19134. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  19135. }
  19136. else {
  19137. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  19138. }
  19139. return this;
  19140. };
  19141. AbstractMesh.prototype.checkOcclusionQuery = function () {
  19142. var engine = this.getEngine();
  19143. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  19144. this._isOccluded = false;
  19145. return;
  19146. }
  19147. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  19148. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  19149. if (isOcclusionQueryAvailable) {
  19150. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  19151. this._isOcclusionQueryInProgress = false;
  19152. this._occlusionInternalRetryCounter = 0;
  19153. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  19154. }
  19155. else {
  19156. this._occlusionInternalRetryCounter++;
  19157. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  19158. this._isOcclusionQueryInProgress = false;
  19159. this._occlusionInternalRetryCounter = 0;
  19160. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  19161. // if strict continue the last state of the object.
  19162. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  19163. }
  19164. else {
  19165. return;
  19166. }
  19167. }
  19168. }
  19169. var scene = this.getScene();
  19170. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  19171. if (!this._occlusionQuery) {
  19172. this._occlusionQuery = engine.createQuery();
  19173. }
  19174. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  19175. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  19176. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  19177. this._isOcclusionQueryInProgress = true;
  19178. };
  19179. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  19180. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  19181. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  19182. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  19183. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  19184. return AbstractMesh;
  19185. }(BABYLON.TransformNode));
  19186. BABYLON.AbstractMesh = AbstractMesh;
  19187. })(BABYLON || (BABYLON = {}));
  19188. //# sourceMappingURL=babylon.abstractMesh.js.map
  19189. var BABYLON;
  19190. (function (BABYLON) {
  19191. /**
  19192. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  19193. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  19194. * 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.
  19195. */
  19196. var Light = /** @class */ (function (_super) {
  19197. __extends(Light, _super);
  19198. /**
  19199. * Creates a Light object in the scene.
  19200. * Documentation : http://doc.babylonjs.com/tutorials/lights
  19201. * @param name The firendly name of the light
  19202. * @param scene The scene the light belongs too
  19203. */
  19204. function Light(name, scene) {
  19205. var _this = _super.call(this, name, scene) || this;
  19206. /**
  19207. * Diffuse gives the basic color to an object.
  19208. */
  19209. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  19210. /**
  19211. * Specular produces a highlight color on an object.
  19212. * Note: This is note affecting PBR materials.
  19213. */
  19214. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  19215. /**
  19216. * Strength of the light.
  19217. * Note: By default it is define in the framework own unit.
  19218. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  19219. */
  19220. _this.intensity = 1.0;
  19221. /**
  19222. * Defines how far from the source the light is impacting in scene units.
  19223. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  19224. */
  19225. _this.range = Number.MAX_VALUE;
  19226. /**
  19227. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  19228. * of light.
  19229. */
  19230. _this._photometricScale = 1.0;
  19231. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  19232. _this._radius = 0.00001;
  19233. /**
  19234. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  19235. * exceeding the number allowed of the materials.
  19236. */
  19237. _this.renderPriority = 0;
  19238. /**
  19239. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  19240. * the current shadow generator.
  19241. */
  19242. _this.shadowEnabled = true;
  19243. _this._excludeWithLayerMask = 0;
  19244. _this._includeOnlyWithLayerMask = 0;
  19245. _this._lightmapMode = 0;
  19246. /**
  19247. * @ignore Internal use only.
  19248. */
  19249. _this._excludedMeshesIds = new Array();
  19250. /**
  19251. * @ignore Internal use only.
  19252. */
  19253. _this._includedOnlyMeshesIds = new Array();
  19254. _this.getScene().addLight(_this);
  19255. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  19256. _this._buildUniformLayout();
  19257. _this.includedOnlyMeshes = new Array();
  19258. _this.excludedMeshes = new Array();
  19259. _this._resyncMeshes();
  19260. return _this;
  19261. }
  19262. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  19263. /**
  19264. * If every light affecting the material is in this lightmapMode,
  19265. * material.lightmapTexture adds or multiplies
  19266. * (depends on material.useLightmapAsShadowmap)
  19267. * after every other light calculations.
  19268. */
  19269. get: function () {
  19270. return Light._LIGHTMAP_DEFAULT;
  19271. },
  19272. enumerable: true,
  19273. configurable: true
  19274. });
  19275. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  19276. /**
  19277. * material.lightmapTexture as only diffuse lighting from this light
  19278. * adds only specular lighting from this light
  19279. * adds dynamic shadows
  19280. */
  19281. get: function () {
  19282. return Light._LIGHTMAP_SPECULAR;
  19283. },
  19284. enumerable: true,
  19285. configurable: true
  19286. });
  19287. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  19288. /**
  19289. * material.lightmapTexture as only lighting
  19290. * no light calculation from this light
  19291. * only adds dynamic shadows from this light
  19292. */
  19293. get: function () {
  19294. return Light._LIGHTMAP_SHADOWSONLY;
  19295. },
  19296. enumerable: true,
  19297. configurable: true
  19298. });
  19299. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  19300. /**
  19301. * Each light type uses the default quantity according to its type:
  19302. * point/spot lights use luminous intensity
  19303. * directional lights use illuminance
  19304. */
  19305. get: function () {
  19306. return Light._INTENSITYMODE_AUTOMATIC;
  19307. },
  19308. enumerable: true,
  19309. configurable: true
  19310. });
  19311. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  19312. /**
  19313. * lumen (lm)
  19314. */
  19315. get: function () {
  19316. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19317. },
  19318. enumerable: true,
  19319. configurable: true
  19320. });
  19321. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19322. /**
  19323. * candela (lm/sr)
  19324. */
  19325. get: function () {
  19326. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19327. },
  19328. enumerable: true,
  19329. configurable: true
  19330. });
  19331. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19332. /**
  19333. * lux (lm/m^2)
  19334. */
  19335. get: function () {
  19336. return Light._INTENSITYMODE_ILLUMINANCE;
  19337. },
  19338. enumerable: true,
  19339. configurable: true
  19340. });
  19341. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19342. /**
  19343. * nit (cd/m^2)
  19344. */
  19345. get: function () {
  19346. return Light._INTENSITYMODE_LUMINANCE;
  19347. },
  19348. enumerable: true,
  19349. configurable: true
  19350. });
  19351. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19352. /**
  19353. * Light type const id of the point light.
  19354. */
  19355. get: function () {
  19356. return Light._LIGHTTYPEID_POINTLIGHT;
  19357. },
  19358. enumerable: true,
  19359. configurable: true
  19360. });
  19361. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19362. /**
  19363. * Light type const id of the directional light.
  19364. */
  19365. get: function () {
  19366. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19367. },
  19368. enumerable: true,
  19369. configurable: true
  19370. });
  19371. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19372. /**
  19373. * Light type const id of the spot light.
  19374. */
  19375. get: function () {
  19376. return Light._LIGHTTYPEID_SPOTLIGHT;
  19377. },
  19378. enumerable: true,
  19379. configurable: true
  19380. });
  19381. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19382. /**
  19383. * Light type const id of the hemispheric light.
  19384. */
  19385. get: function () {
  19386. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19387. },
  19388. enumerable: true,
  19389. configurable: true
  19390. });
  19391. Object.defineProperty(Light.prototype, "intensityMode", {
  19392. /**
  19393. * Gets the photometric scale used to interpret the intensity.
  19394. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19395. */
  19396. get: function () {
  19397. return this._intensityMode;
  19398. },
  19399. /**
  19400. * Sets the photometric scale used to interpret the intensity.
  19401. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19402. */
  19403. set: function (value) {
  19404. this._intensityMode = value;
  19405. this._computePhotometricScale();
  19406. },
  19407. enumerable: true,
  19408. configurable: true
  19409. });
  19410. ;
  19411. ;
  19412. Object.defineProperty(Light.prototype, "radius", {
  19413. /**
  19414. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19415. */
  19416. get: function () {
  19417. return this._radius;
  19418. },
  19419. /**
  19420. * sets the light radius used by PBR Materials to simulate soft area lights.
  19421. */
  19422. set: function (value) {
  19423. this._radius = value;
  19424. this._computePhotometricScale();
  19425. },
  19426. enumerable: true,
  19427. configurable: true
  19428. });
  19429. ;
  19430. ;
  19431. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19432. /**
  19433. * Gets the only meshes impacted by this light.
  19434. */
  19435. get: function () {
  19436. return this._includedOnlyMeshes;
  19437. },
  19438. /**
  19439. * Sets the only meshes impacted by this light.
  19440. */
  19441. set: function (value) {
  19442. this._includedOnlyMeshes = value;
  19443. this._hookArrayForIncludedOnly(value);
  19444. },
  19445. enumerable: true,
  19446. configurable: true
  19447. });
  19448. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19449. /**
  19450. * Gets the meshes not impacted by this light.
  19451. */
  19452. get: function () {
  19453. return this._excludedMeshes;
  19454. },
  19455. /**
  19456. * Sets the meshes not impacted by this light.
  19457. */
  19458. set: function (value) {
  19459. this._excludedMeshes = value;
  19460. this._hookArrayForExcluded(value);
  19461. },
  19462. enumerable: true,
  19463. configurable: true
  19464. });
  19465. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19466. /**
  19467. * Gets the layer id use to find what meshes are not impacted by the light.
  19468. * Inactive if 0
  19469. */
  19470. get: function () {
  19471. return this._excludeWithLayerMask;
  19472. },
  19473. /**
  19474. * Sets the layer id use to find what meshes are not impacted by the light.
  19475. * Inactive if 0
  19476. */
  19477. set: function (value) {
  19478. this._excludeWithLayerMask = value;
  19479. this._resyncMeshes();
  19480. },
  19481. enumerable: true,
  19482. configurable: true
  19483. });
  19484. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19485. /**
  19486. * Gets the layer id use to find what meshes are impacted by the light.
  19487. * Inactive if 0
  19488. */
  19489. get: function () {
  19490. return this._includeOnlyWithLayerMask;
  19491. },
  19492. /**
  19493. * Sets the layer id use to find what meshes are impacted by the light.
  19494. * Inactive if 0
  19495. */
  19496. set: function (value) {
  19497. this._includeOnlyWithLayerMask = value;
  19498. this._resyncMeshes();
  19499. },
  19500. enumerable: true,
  19501. configurable: true
  19502. });
  19503. Object.defineProperty(Light.prototype, "lightmapMode", {
  19504. /**
  19505. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19506. */
  19507. get: function () {
  19508. return this._lightmapMode;
  19509. },
  19510. /**
  19511. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19512. */
  19513. set: function (value) {
  19514. if (this._lightmapMode === value) {
  19515. return;
  19516. }
  19517. this._lightmapMode = value;
  19518. this._markMeshesAsLightDirty();
  19519. },
  19520. enumerable: true,
  19521. configurable: true
  19522. });
  19523. /**
  19524. * Returns the string "Light".
  19525. * @returns the class name
  19526. */
  19527. Light.prototype.getClassName = function () {
  19528. return "Light";
  19529. };
  19530. /**
  19531. * Converts the light information to a readable string for debug purpose.
  19532. * @param fullDetails Supports for multiple levels of logging within scene loading
  19533. * @returns the human readable light info
  19534. */
  19535. Light.prototype.toString = function (fullDetails) {
  19536. var ret = "Name: " + this.name;
  19537. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19538. if (this.animations) {
  19539. for (var i = 0; i < this.animations.length; i++) {
  19540. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19541. }
  19542. }
  19543. if (fullDetails) {
  19544. }
  19545. return ret;
  19546. };
  19547. /**
  19548. * Set the enabled state of this node.
  19549. * @param value - the new enabled state
  19550. * @see isEnabled
  19551. */
  19552. Light.prototype.setEnabled = function (value) {
  19553. _super.prototype.setEnabled.call(this, value);
  19554. this._resyncMeshes();
  19555. };
  19556. /**
  19557. * Returns the Light associated shadow generator if any.
  19558. * @return the associated shadow generator.
  19559. */
  19560. Light.prototype.getShadowGenerator = function () {
  19561. return this._shadowGenerator;
  19562. };
  19563. /**
  19564. * Returns a Vector3, the absolute light position in the World.
  19565. * @returns the world space position of the light
  19566. */
  19567. Light.prototype.getAbsolutePosition = function () {
  19568. return BABYLON.Vector3.Zero();
  19569. };
  19570. /**
  19571. * Specifies if the light will affect the passed mesh.
  19572. * @param mesh The mesh to test against the light
  19573. * @return true the mesh is affected otherwise, false.
  19574. */
  19575. Light.prototype.canAffectMesh = function (mesh) {
  19576. if (!mesh) {
  19577. return true;
  19578. }
  19579. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19580. return false;
  19581. }
  19582. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19583. return false;
  19584. }
  19585. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19586. return false;
  19587. }
  19588. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19589. return false;
  19590. }
  19591. return true;
  19592. };
  19593. /**
  19594. * Computes and Returns the light World matrix.
  19595. * @returns the world matrix
  19596. */
  19597. Light.prototype.getWorldMatrix = function () {
  19598. this._currentRenderId = this.getScene().getRenderId();
  19599. var worldMatrix = this._getWorldMatrix();
  19600. if (this.parent && this.parent.getWorldMatrix) {
  19601. if (!this._parentedWorldMatrix) {
  19602. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19603. }
  19604. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19605. this._markSyncedWithParent();
  19606. return this._parentedWorldMatrix;
  19607. }
  19608. return worldMatrix;
  19609. };
  19610. /**
  19611. * Sort function to order lights for rendering.
  19612. * @param a First Light object to compare to second.
  19613. * @param b Second Light object to compare first.
  19614. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19615. */
  19616. Light.CompareLightsPriority = function (a, b) {
  19617. //shadow-casting lights have priority over non-shadow-casting lights
  19618. //the renderPrioirty is a secondary sort criterion
  19619. if (a.shadowEnabled !== b.shadowEnabled) {
  19620. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19621. }
  19622. return b.renderPriority - a.renderPriority;
  19623. };
  19624. /**
  19625. * Releases resources associated with this node.
  19626. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19627. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19628. */
  19629. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19630. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19631. if (this._shadowGenerator) {
  19632. this._shadowGenerator.dispose();
  19633. this._shadowGenerator = null;
  19634. }
  19635. // Animations
  19636. this.getScene().stopAnimation(this);
  19637. // Remove from meshes
  19638. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19639. var mesh = _a[_i];
  19640. mesh._removeLightSource(this);
  19641. }
  19642. this._uniformBuffer.dispose();
  19643. // Remove from scene
  19644. this.getScene().removeLight(this);
  19645. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19646. };
  19647. /**
  19648. * Returns the light type ID (integer).
  19649. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19650. */
  19651. Light.prototype.getTypeID = function () {
  19652. return 0;
  19653. };
  19654. /**
  19655. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19656. * @returns the scaled intensity in intensity mode unit
  19657. */
  19658. Light.prototype.getScaledIntensity = function () {
  19659. return this._photometricScale * this.intensity;
  19660. };
  19661. /**
  19662. * Returns a new Light object, named "name", from the current one.
  19663. * @param name The name of the cloned light
  19664. * @returns the new created light
  19665. */
  19666. Light.prototype.clone = function (name) {
  19667. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19668. if (!constructor) {
  19669. return null;
  19670. }
  19671. return BABYLON.SerializationHelper.Clone(constructor, this);
  19672. };
  19673. /**
  19674. * Serializes the current light into a Serialization object.
  19675. * @returns the serialized object.
  19676. */
  19677. Light.prototype.serialize = function () {
  19678. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19679. // Type
  19680. serializationObject.type = this.getTypeID();
  19681. // Parent
  19682. if (this.parent) {
  19683. serializationObject.parentId = this.parent.id;
  19684. }
  19685. // Inclusion / exclusions
  19686. if (this.excludedMeshes.length > 0) {
  19687. serializationObject.excludedMeshesIds = [];
  19688. this.excludedMeshes.forEach(function (mesh) {
  19689. serializationObject.excludedMeshesIds.push(mesh.id);
  19690. });
  19691. }
  19692. if (this.includedOnlyMeshes.length > 0) {
  19693. serializationObject.includedOnlyMeshesIds = [];
  19694. this.includedOnlyMeshes.forEach(function (mesh) {
  19695. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19696. });
  19697. }
  19698. // Animations
  19699. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19700. serializationObject.ranges = this.serializeAnimationRanges();
  19701. return serializationObject;
  19702. };
  19703. /**
  19704. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19705. * This new light is named "name" and added to the passed scene.
  19706. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19707. * @param name The friendly name of the light
  19708. * @param scene The scene the new light will belong to
  19709. * @returns the constructor function
  19710. */
  19711. Light.GetConstructorFromName = function (type, name, scene) {
  19712. switch (type) {
  19713. case 0:
  19714. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19715. case 1:
  19716. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19717. case 2:
  19718. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19719. case 3:
  19720. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19721. }
  19722. return null;
  19723. };
  19724. /**
  19725. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19726. * @param parsedLight The JSON representation of the light
  19727. * @param scene The scene to create the parsed light in
  19728. * @returns the created light after parsing
  19729. */
  19730. Light.Parse = function (parsedLight, scene) {
  19731. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19732. if (!constructor) {
  19733. return null;
  19734. }
  19735. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19736. // Inclusion / exclusions
  19737. if (parsedLight.excludedMeshesIds) {
  19738. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19739. }
  19740. if (parsedLight.includedOnlyMeshesIds) {
  19741. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19742. }
  19743. // Parent
  19744. if (parsedLight.parentId) {
  19745. light._waitingParentId = parsedLight.parentId;
  19746. }
  19747. // Animations
  19748. if (parsedLight.animations) {
  19749. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19750. var parsedAnimation = parsedLight.animations[animationIndex];
  19751. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19752. }
  19753. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19754. }
  19755. if (parsedLight.autoAnimate) {
  19756. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19757. }
  19758. return light;
  19759. };
  19760. Light.prototype._hookArrayForExcluded = function (array) {
  19761. var _this = this;
  19762. var oldPush = array.push;
  19763. array.push = function () {
  19764. var items = [];
  19765. for (var _i = 0; _i < arguments.length; _i++) {
  19766. items[_i] = arguments[_i];
  19767. }
  19768. var result = oldPush.apply(array, items);
  19769. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19770. var item = items_1[_a];
  19771. item._resyncLighSource(_this);
  19772. }
  19773. return result;
  19774. };
  19775. var oldSplice = array.splice;
  19776. array.splice = function (index, deleteCount) {
  19777. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19778. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19779. var item = deleted_1[_i];
  19780. item._resyncLighSource(_this);
  19781. }
  19782. return deleted;
  19783. };
  19784. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19785. var item = array_1[_i];
  19786. item._resyncLighSource(this);
  19787. }
  19788. };
  19789. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19790. var _this = this;
  19791. var oldPush = array.push;
  19792. array.push = function () {
  19793. var items = [];
  19794. for (var _i = 0; _i < arguments.length; _i++) {
  19795. items[_i] = arguments[_i];
  19796. }
  19797. var result = oldPush.apply(array, items);
  19798. _this._resyncMeshes();
  19799. return result;
  19800. };
  19801. var oldSplice = array.splice;
  19802. array.splice = function (index, deleteCount) {
  19803. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19804. _this._resyncMeshes();
  19805. return deleted;
  19806. };
  19807. this._resyncMeshes();
  19808. };
  19809. Light.prototype._resyncMeshes = function () {
  19810. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19811. var mesh = _a[_i];
  19812. mesh._resyncLighSource(this);
  19813. }
  19814. };
  19815. /**
  19816. * Forces the meshes to update their light related information in their rendering used effects
  19817. * @ignore Internal Use Only
  19818. */
  19819. Light.prototype._markMeshesAsLightDirty = function () {
  19820. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19821. var mesh = _a[_i];
  19822. if (mesh._lightSources.indexOf(this) !== -1) {
  19823. mesh._markSubMeshesAsLightDirty();
  19824. }
  19825. }
  19826. };
  19827. /**
  19828. * Recomputes the cached photometric scale if needed.
  19829. */
  19830. Light.prototype._computePhotometricScale = function () {
  19831. this._photometricScale = this._getPhotometricScale();
  19832. this.getScene().resetCachedMaterial();
  19833. };
  19834. /**
  19835. * Returns the Photometric Scale according to the light type and intensity mode.
  19836. */
  19837. Light.prototype._getPhotometricScale = function () {
  19838. var photometricScale = 0.0;
  19839. var lightTypeID = this.getTypeID();
  19840. //get photometric mode
  19841. var photometricMode = this.intensityMode;
  19842. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19843. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19844. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19845. }
  19846. else {
  19847. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19848. }
  19849. }
  19850. //compute photometric scale
  19851. switch (lightTypeID) {
  19852. case Light.LIGHTTYPEID_POINTLIGHT:
  19853. case Light.LIGHTTYPEID_SPOTLIGHT:
  19854. switch (photometricMode) {
  19855. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19856. photometricScale = 1.0 / (4.0 * Math.PI);
  19857. break;
  19858. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19859. photometricScale = 1.0;
  19860. break;
  19861. case Light.INTENSITYMODE_LUMINANCE:
  19862. photometricScale = this.radius * this.radius;
  19863. break;
  19864. }
  19865. break;
  19866. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19867. switch (photometricMode) {
  19868. case Light.INTENSITYMODE_ILLUMINANCE:
  19869. photometricScale = 1.0;
  19870. break;
  19871. case Light.INTENSITYMODE_LUMINANCE:
  19872. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19873. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19874. var apexAngleRadians = this.radius;
  19875. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19876. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19877. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19878. photometricScale = solidAngle;
  19879. break;
  19880. }
  19881. break;
  19882. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19883. // No fall off in hemisperic light.
  19884. photometricScale = 1.0;
  19885. break;
  19886. }
  19887. return photometricScale;
  19888. };
  19889. /**
  19890. * Reorder the light in the scene according to their defined priority.
  19891. * @ignore Internal Use Only
  19892. */
  19893. Light.prototype._reorderLightsInScene = function () {
  19894. var scene = this.getScene();
  19895. if (this._renderPriority != 0) {
  19896. scene.requireLightSorting = true;
  19897. }
  19898. this.getScene().sortLightsByPriority();
  19899. };
  19900. //lightmapMode Consts
  19901. Light._LIGHTMAP_DEFAULT = 0;
  19902. Light._LIGHTMAP_SPECULAR = 1;
  19903. Light._LIGHTMAP_SHADOWSONLY = 2;
  19904. // Intensity Mode Consts
  19905. Light._INTENSITYMODE_AUTOMATIC = 0;
  19906. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19907. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19908. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19909. Light._INTENSITYMODE_LUMINANCE = 4;
  19910. // Light types ids const.
  19911. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19912. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19913. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19914. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19915. __decorate([
  19916. BABYLON.serializeAsColor3()
  19917. ], Light.prototype, "diffuse", void 0);
  19918. __decorate([
  19919. BABYLON.serializeAsColor3()
  19920. ], Light.prototype, "specular", void 0);
  19921. __decorate([
  19922. BABYLON.serialize()
  19923. ], Light.prototype, "intensity", void 0);
  19924. __decorate([
  19925. BABYLON.serialize()
  19926. ], Light.prototype, "range", void 0);
  19927. __decorate([
  19928. BABYLON.serialize()
  19929. ], Light.prototype, "intensityMode", null);
  19930. __decorate([
  19931. BABYLON.serialize()
  19932. ], Light.prototype, "radius", null);
  19933. __decorate([
  19934. BABYLON.serialize()
  19935. ], Light.prototype, "_renderPriority", void 0);
  19936. __decorate([
  19937. BABYLON.expandToProperty("_reorderLightsInScene")
  19938. ], Light.prototype, "renderPriority", void 0);
  19939. __decorate([
  19940. BABYLON.serialize()
  19941. ], Light.prototype, "shadowEnabled", void 0);
  19942. __decorate([
  19943. BABYLON.serialize("excludeWithLayerMask")
  19944. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19945. __decorate([
  19946. BABYLON.serialize("includeOnlyWithLayerMask")
  19947. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19948. __decorate([
  19949. BABYLON.serialize("lightmapMode")
  19950. ], Light.prototype, "_lightmapMode", void 0);
  19951. return Light;
  19952. }(BABYLON.Node));
  19953. BABYLON.Light = Light;
  19954. })(BABYLON || (BABYLON = {}));
  19955. //# sourceMappingURL=babylon.light.js.map
  19956. var BABYLON;
  19957. (function (BABYLON) {
  19958. var Camera = /** @class */ (function (_super) {
  19959. __extends(Camera, _super);
  19960. function Camera(name, position, scene) {
  19961. var _this = _super.call(this, name, scene) || this;
  19962. /**
  19963. * The vector the camera should consider as up.
  19964. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19965. */
  19966. _this.upVector = BABYLON.Vector3.Up();
  19967. _this.orthoLeft = null;
  19968. _this.orthoRight = null;
  19969. _this.orthoBottom = null;
  19970. _this.orthoTop = null;
  19971. /**
  19972. * FOV is set in Radians. (default is 0.8)
  19973. */
  19974. _this.fov = 0.8;
  19975. _this.minZ = 1;
  19976. _this.maxZ = 10000.0;
  19977. _this.inertia = 0.9;
  19978. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19979. _this.isIntermediate = false;
  19980. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  19981. /**
  19982. * Restricts the camera to viewing objects with the same layerMask.
  19983. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  19984. */
  19985. _this.layerMask = 0x0FFFFFFF;
  19986. /**
  19987. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  19988. */
  19989. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  19990. // Camera rig members
  19991. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  19992. _this._rigCameras = new Array();
  19993. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  19994. _this._skipRendering = false;
  19995. _this.customRenderTargets = new Array();
  19996. // Observables
  19997. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  19998. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  19999. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  20000. _this.onRestoreStateObservable = new BABYLON.Observable();
  20001. // Cache
  20002. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  20003. _this._projectionMatrix = new BABYLON.Matrix();
  20004. _this._doNotComputeProjectionMatrix = false;
  20005. _this._postProcesses = new Array();
  20006. _this._transformMatrix = BABYLON.Matrix.Zero();
  20007. _this._activeMeshes = new BABYLON.SmartArray(256);
  20008. _this._globalPosition = BABYLON.Vector3.Zero();
  20009. _this._refreshFrustumPlanes = true;
  20010. _this.getScene().addCamera(_this);
  20011. if (!_this.getScene().activeCamera) {
  20012. _this.getScene().activeCamera = _this;
  20013. }
  20014. _this.position = position;
  20015. return _this;
  20016. }
  20017. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  20018. get: function () {
  20019. return Camera._PERSPECTIVE_CAMERA;
  20020. },
  20021. enumerable: true,
  20022. configurable: true
  20023. });
  20024. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  20025. get: function () {
  20026. return Camera._ORTHOGRAPHIC_CAMERA;
  20027. },
  20028. enumerable: true,
  20029. configurable: true
  20030. });
  20031. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  20032. /**
  20033. * This is the default FOV mode for perspective cameras.
  20034. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  20035. *
  20036. */
  20037. get: function () {
  20038. return Camera._FOVMODE_VERTICAL_FIXED;
  20039. },
  20040. enumerable: true,
  20041. configurable: true
  20042. });
  20043. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  20044. /**
  20045. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  20046. *
  20047. */
  20048. get: function () {
  20049. return Camera._FOVMODE_HORIZONTAL_FIXED;
  20050. },
  20051. enumerable: true,
  20052. configurable: true
  20053. });
  20054. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  20055. get: function () {
  20056. return Camera._RIG_MODE_NONE;
  20057. },
  20058. enumerable: true,
  20059. configurable: true
  20060. });
  20061. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  20062. get: function () {
  20063. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  20064. },
  20065. enumerable: true,
  20066. configurable: true
  20067. });
  20068. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  20069. get: function () {
  20070. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  20071. },
  20072. enumerable: true,
  20073. configurable: true
  20074. });
  20075. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  20076. get: function () {
  20077. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20078. },
  20079. enumerable: true,
  20080. configurable: true
  20081. });
  20082. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  20083. get: function () {
  20084. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  20085. },
  20086. enumerable: true,
  20087. configurable: true
  20088. });
  20089. Object.defineProperty(Camera, "RIG_MODE_VR", {
  20090. get: function () {
  20091. return Camera._RIG_MODE_VR;
  20092. },
  20093. enumerable: true,
  20094. configurable: true
  20095. });
  20096. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  20097. get: function () {
  20098. return Camera._RIG_MODE_WEBVR;
  20099. },
  20100. enumerable: true,
  20101. configurable: true
  20102. });
  20103. /**
  20104. * Store current camera state (fov, position, etc..)
  20105. */
  20106. Camera.prototype.storeState = function () {
  20107. this._stateStored = true;
  20108. this._storedFov = this.fov;
  20109. return this;
  20110. };
  20111. /**
  20112. * Restores the camera state values if it has been stored. You must call storeState() first
  20113. */
  20114. Camera.prototype._restoreStateValues = function () {
  20115. if (!this._stateStored) {
  20116. return false;
  20117. }
  20118. this.fov = this._storedFov;
  20119. return true;
  20120. };
  20121. /**
  20122. * Restored camera state. You must call storeState() first
  20123. */
  20124. Camera.prototype.restoreState = function () {
  20125. if (this._restoreStateValues()) {
  20126. this.onRestoreStateObservable.notifyObservers(this);
  20127. return true;
  20128. }
  20129. return false;
  20130. };
  20131. Camera.prototype.getClassName = function () {
  20132. return "Camera";
  20133. };
  20134. /**
  20135. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20136. */
  20137. Camera.prototype.toString = function (fullDetails) {
  20138. var ret = "Name: " + this.name;
  20139. ret += ", type: " + this.getClassName();
  20140. if (this.animations) {
  20141. for (var i = 0; i < this.animations.length; i++) {
  20142. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20143. }
  20144. }
  20145. if (fullDetails) {
  20146. }
  20147. return ret;
  20148. };
  20149. Object.defineProperty(Camera.prototype, "globalPosition", {
  20150. get: function () {
  20151. return this._globalPosition;
  20152. },
  20153. enumerable: true,
  20154. configurable: true
  20155. });
  20156. Camera.prototype.getActiveMeshes = function () {
  20157. return this._activeMeshes;
  20158. };
  20159. Camera.prototype.isActiveMesh = function (mesh) {
  20160. return (this._activeMeshes.indexOf(mesh) !== -1);
  20161. };
  20162. //Cache
  20163. Camera.prototype._initCache = function () {
  20164. _super.prototype._initCache.call(this);
  20165. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20166. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20167. this._cache.mode = undefined;
  20168. this._cache.minZ = undefined;
  20169. this._cache.maxZ = undefined;
  20170. this._cache.fov = undefined;
  20171. this._cache.fovMode = undefined;
  20172. this._cache.aspectRatio = undefined;
  20173. this._cache.orthoLeft = undefined;
  20174. this._cache.orthoRight = undefined;
  20175. this._cache.orthoBottom = undefined;
  20176. this._cache.orthoTop = undefined;
  20177. this._cache.renderWidth = undefined;
  20178. this._cache.renderHeight = undefined;
  20179. };
  20180. Camera.prototype._updateCache = function (ignoreParentClass) {
  20181. if (!ignoreParentClass) {
  20182. _super.prototype._updateCache.call(this);
  20183. }
  20184. this._cache.position.copyFrom(this.position);
  20185. this._cache.upVector.copyFrom(this.upVector);
  20186. };
  20187. // Synchronized
  20188. Camera.prototype._isSynchronized = function () {
  20189. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  20190. };
  20191. Camera.prototype._isSynchronizedViewMatrix = function () {
  20192. if (!_super.prototype._isSynchronized.call(this))
  20193. return false;
  20194. return this._cache.position.equals(this.position)
  20195. && this._cache.upVector.equals(this.upVector)
  20196. && this.isSynchronizedWithParent();
  20197. };
  20198. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  20199. var check = this._cache.mode === this.mode
  20200. && this._cache.minZ === this.minZ
  20201. && this._cache.maxZ === this.maxZ;
  20202. if (!check) {
  20203. return false;
  20204. }
  20205. var engine = this.getEngine();
  20206. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20207. check = this._cache.fov === this.fov
  20208. && this._cache.fovMode === this.fovMode
  20209. && this._cache.aspectRatio === engine.getAspectRatio(this);
  20210. }
  20211. else {
  20212. check = this._cache.orthoLeft === this.orthoLeft
  20213. && this._cache.orthoRight === this.orthoRight
  20214. && this._cache.orthoBottom === this.orthoBottom
  20215. && this._cache.orthoTop === this.orthoTop
  20216. && this._cache.renderWidth === engine.getRenderWidth()
  20217. && this._cache.renderHeight === engine.getRenderHeight();
  20218. }
  20219. return check;
  20220. };
  20221. // Controls
  20222. Camera.prototype.attachControl = function (element, noPreventDefault) {
  20223. };
  20224. Camera.prototype.detachControl = function (element) {
  20225. };
  20226. Camera.prototype.update = function () {
  20227. this._checkInputs();
  20228. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20229. this._updateRigCameras();
  20230. }
  20231. };
  20232. Camera.prototype._checkInputs = function () {
  20233. this.onAfterCheckInputsObservable.notifyObservers(this);
  20234. };
  20235. Object.defineProperty(Camera.prototype, "rigCameras", {
  20236. get: function () {
  20237. return this._rigCameras;
  20238. },
  20239. enumerable: true,
  20240. configurable: true
  20241. });
  20242. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  20243. get: function () {
  20244. return this._rigPostProcess;
  20245. },
  20246. enumerable: true,
  20247. configurable: true
  20248. });
  20249. /**
  20250. * Internal, gets the first post proces.
  20251. * @returns the first post process to be run on this camera.
  20252. */
  20253. Camera.prototype._getFirstPostProcess = function () {
  20254. for (var pp in this._postProcesses) {
  20255. if (this._postProcesses[pp] !== null) {
  20256. return this._postProcesses[pp];
  20257. }
  20258. }
  20259. return null;
  20260. };
  20261. Camera.prototype._cascadePostProcessesToRigCams = function () {
  20262. // invalidate framebuffer
  20263. var firstPostProcess = this._getFirstPostProcess();
  20264. if (firstPostProcess) {
  20265. firstPostProcess.markTextureDirty();
  20266. }
  20267. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  20268. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  20269. var cam = this._rigCameras[i];
  20270. var rigPostProcess = cam._rigPostProcess;
  20271. // for VR rig, there does not have to be a post process
  20272. if (rigPostProcess) {
  20273. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  20274. if (isPass) {
  20275. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  20276. cam.isIntermediate = this._postProcesses.length === 0;
  20277. }
  20278. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  20279. rigPostProcess.markTextureDirty();
  20280. }
  20281. else {
  20282. cam._postProcesses = this._postProcesses.slice(0);
  20283. }
  20284. }
  20285. };
  20286. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  20287. if (insertAt === void 0) { insertAt = null; }
  20288. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  20289. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  20290. return 0;
  20291. }
  20292. if (insertAt == null || insertAt < 0) {
  20293. this._postProcesses.push(postProcess);
  20294. }
  20295. else if (this._postProcesses[insertAt] === null) {
  20296. this._postProcesses[insertAt] = postProcess;
  20297. }
  20298. else {
  20299. this._postProcesses.splice(insertAt, 0, postProcess);
  20300. }
  20301. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20302. return this._postProcesses.indexOf(postProcess);
  20303. };
  20304. Camera.prototype.detachPostProcess = function (postProcess) {
  20305. var idx = this._postProcesses.indexOf(postProcess);
  20306. if (idx !== -1) {
  20307. this._postProcesses[idx] = null;
  20308. }
  20309. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20310. };
  20311. Camera.prototype.getWorldMatrix = function () {
  20312. if (!this._worldMatrix) {
  20313. this._worldMatrix = BABYLON.Matrix.Identity();
  20314. }
  20315. var viewMatrix = this.getViewMatrix();
  20316. viewMatrix.invertToRef(this._worldMatrix);
  20317. return this._worldMatrix;
  20318. };
  20319. Camera.prototype._getViewMatrix = function () {
  20320. return BABYLON.Matrix.Identity();
  20321. };
  20322. Camera.prototype.getViewMatrix = function (force) {
  20323. if (!force && this._isSynchronizedViewMatrix()) {
  20324. return this._computedViewMatrix;
  20325. }
  20326. this.updateCache();
  20327. this._computedViewMatrix = this._getViewMatrix();
  20328. this._currentRenderId = this.getScene().getRenderId();
  20329. this._refreshFrustumPlanes = true;
  20330. if (!this.parent || !this.parent.getWorldMatrix) {
  20331. this._globalPosition.copyFrom(this.position);
  20332. }
  20333. else {
  20334. if (!this._worldMatrix) {
  20335. this._worldMatrix = BABYLON.Matrix.Identity();
  20336. }
  20337. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20338. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20339. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20340. this._computedViewMatrix.invert();
  20341. this._markSyncedWithParent();
  20342. }
  20343. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20344. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20345. }
  20346. this.onViewMatrixChangedObservable.notifyObservers(this);
  20347. return this._computedViewMatrix;
  20348. };
  20349. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20350. this._doNotComputeProjectionMatrix = true;
  20351. if (projection !== undefined) {
  20352. this._projectionMatrix = projection;
  20353. }
  20354. };
  20355. ;
  20356. Camera.prototype.unfreezeProjectionMatrix = function () {
  20357. this._doNotComputeProjectionMatrix = false;
  20358. };
  20359. ;
  20360. Camera.prototype.getProjectionMatrix = function (force) {
  20361. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20362. return this._projectionMatrix;
  20363. }
  20364. // Cache
  20365. this._cache.mode = this.mode;
  20366. this._cache.minZ = this.minZ;
  20367. this._cache.maxZ = this.maxZ;
  20368. // Matrix
  20369. this._refreshFrustumPlanes = true;
  20370. var engine = this.getEngine();
  20371. var scene = this.getScene();
  20372. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20373. this._cache.fov = this.fov;
  20374. this._cache.fovMode = this.fovMode;
  20375. this._cache.aspectRatio = engine.getAspectRatio(this);
  20376. if (this.minZ <= 0) {
  20377. this.minZ = 0.1;
  20378. }
  20379. if (scene.useRightHandedSystem) {
  20380. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20381. }
  20382. else {
  20383. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20384. }
  20385. }
  20386. else {
  20387. var halfWidth = engine.getRenderWidth() / 2.0;
  20388. var halfHeight = engine.getRenderHeight() / 2.0;
  20389. if (scene.useRightHandedSystem) {
  20390. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20391. }
  20392. else {
  20393. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20394. }
  20395. this._cache.orthoLeft = this.orthoLeft;
  20396. this._cache.orthoRight = this.orthoRight;
  20397. this._cache.orthoBottom = this.orthoBottom;
  20398. this._cache.orthoTop = this.orthoTop;
  20399. this._cache.renderWidth = engine.getRenderWidth();
  20400. this._cache.renderHeight = engine.getRenderHeight();
  20401. }
  20402. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20403. return this._projectionMatrix;
  20404. };
  20405. Camera.prototype.getTranformationMatrix = function () {
  20406. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20407. return this._transformMatrix;
  20408. };
  20409. Camera.prototype.updateFrustumPlanes = function () {
  20410. if (!this._refreshFrustumPlanes) {
  20411. return;
  20412. }
  20413. this.getTranformationMatrix();
  20414. if (!this._frustumPlanes) {
  20415. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20416. }
  20417. else {
  20418. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20419. }
  20420. this._refreshFrustumPlanes = false;
  20421. };
  20422. Camera.prototype.isInFrustum = function (target) {
  20423. this.updateFrustumPlanes();
  20424. return target.isInFrustum(this._frustumPlanes);
  20425. };
  20426. Camera.prototype.isCompletelyInFrustum = function (target) {
  20427. this.updateFrustumPlanes();
  20428. return target.isCompletelyInFrustum(this._frustumPlanes);
  20429. };
  20430. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20431. if (length === void 0) { length = 100; }
  20432. if (!transform) {
  20433. transform = this.getWorldMatrix();
  20434. }
  20435. if (!origin) {
  20436. origin = this.position;
  20437. }
  20438. var forward = new BABYLON.Vector3(0, 0, 1);
  20439. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20440. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20441. return new BABYLON.Ray(origin, direction, length);
  20442. };
  20443. /**
  20444. * Releases resources associated with this node.
  20445. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20446. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20447. */
  20448. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20449. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20450. // Observables
  20451. this.onViewMatrixChangedObservable.clear();
  20452. this.onProjectionMatrixChangedObservable.clear();
  20453. this.onAfterCheckInputsObservable.clear();
  20454. this.onRestoreStateObservable.clear();
  20455. // Inputs
  20456. if (this.inputs) {
  20457. this.inputs.clear();
  20458. }
  20459. // Animations
  20460. this.getScene().stopAnimation(this);
  20461. // Remove from scene
  20462. this.getScene().removeCamera(this);
  20463. while (this._rigCameras.length > 0) {
  20464. var camera = this._rigCameras.pop();
  20465. if (camera) {
  20466. camera.dispose();
  20467. }
  20468. }
  20469. // Postprocesses
  20470. if (this._rigPostProcess) {
  20471. this._rigPostProcess.dispose(this);
  20472. this._rigPostProcess = null;
  20473. this._postProcesses = [];
  20474. }
  20475. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20476. this._rigPostProcess = null;
  20477. this._postProcesses = [];
  20478. }
  20479. else {
  20480. var i = this._postProcesses.length;
  20481. while (--i >= 0) {
  20482. var postProcess = this._postProcesses[i];
  20483. if (postProcess) {
  20484. postProcess.dispose(this);
  20485. }
  20486. }
  20487. }
  20488. // Render targets
  20489. var i = this.customRenderTargets.length;
  20490. while (--i >= 0) {
  20491. this.customRenderTargets[i].dispose();
  20492. }
  20493. this.customRenderTargets = [];
  20494. // Active Meshes
  20495. this._activeMeshes.dispose();
  20496. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20497. };
  20498. Object.defineProperty(Camera.prototype, "leftCamera", {
  20499. // ---- Camera rigs section ----
  20500. get: function () {
  20501. if (this._rigCameras.length < 1) {
  20502. return null;
  20503. }
  20504. return this._rigCameras[0];
  20505. },
  20506. enumerable: true,
  20507. configurable: true
  20508. });
  20509. Object.defineProperty(Camera.prototype, "rightCamera", {
  20510. get: function () {
  20511. if (this._rigCameras.length < 2) {
  20512. return null;
  20513. }
  20514. return this._rigCameras[1];
  20515. },
  20516. enumerable: true,
  20517. configurable: true
  20518. });
  20519. Camera.prototype.getLeftTarget = function () {
  20520. if (this._rigCameras.length < 1) {
  20521. return null;
  20522. }
  20523. return this._rigCameras[0].getTarget();
  20524. };
  20525. Camera.prototype.getRightTarget = function () {
  20526. if (this._rigCameras.length < 2) {
  20527. return null;
  20528. }
  20529. return this._rigCameras[1].getTarget();
  20530. };
  20531. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20532. if (this.cameraRigMode === mode) {
  20533. return;
  20534. }
  20535. while (this._rigCameras.length > 0) {
  20536. var camera = this._rigCameras.pop();
  20537. if (camera) {
  20538. camera.dispose();
  20539. }
  20540. }
  20541. this.cameraRigMode = mode;
  20542. this._cameraRigParams = {};
  20543. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20544. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20545. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20546. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20547. // create the rig cameras, unless none
  20548. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20549. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20550. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20551. if (leftCamera && rightCamera) {
  20552. this._rigCameras.push(leftCamera);
  20553. this._rigCameras.push(rightCamera);
  20554. }
  20555. }
  20556. switch (this.cameraRigMode) {
  20557. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20558. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20559. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20560. break;
  20561. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20562. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20563. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20564. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20565. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20566. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20567. break;
  20568. case Camera.RIG_MODE_VR:
  20569. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20570. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20571. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20572. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20573. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20574. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20575. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20576. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20577. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20578. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20579. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20580. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20581. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20582. if (metrics.compensateDistortion) {
  20583. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20584. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20585. }
  20586. break;
  20587. case Camera.RIG_MODE_WEBVR:
  20588. if (rigParams.vrDisplay) {
  20589. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20590. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20591. //Left eye
  20592. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20593. this._rigCameras[0].setCameraRigParameter("left", true);
  20594. //leaving this for future reference
  20595. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20596. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20597. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20598. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20599. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20600. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20601. this._rigCameras[0].parent = this;
  20602. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20603. //Right eye
  20604. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20605. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20606. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20607. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20608. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20609. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20610. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20611. this._rigCameras[1].parent = this;
  20612. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20613. if (Camera.UseAlternateWebVRRendering) {
  20614. this._rigCameras[1]._skipRendering = true;
  20615. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20616. }
  20617. }
  20618. break;
  20619. }
  20620. this._cascadePostProcessesToRigCams();
  20621. this.update();
  20622. };
  20623. Camera.prototype._getVRProjectionMatrix = function () {
  20624. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20625. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20626. return this._projectionMatrix;
  20627. };
  20628. Camera.prototype._updateCameraRotationMatrix = function () {
  20629. //Here for WebVR
  20630. };
  20631. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20632. //Here for WebVR
  20633. };
  20634. /**
  20635. * This function MUST be overwritten by the different WebVR cameras available.
  20636. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20637. */
  20638. Camera.prototype._getWebVRProjectionMatrix = function () {
  20639. return BABYLON.Matrix.Identity();
  20640. };
  20641. /**
  20642. * This function MUST be overwritten by the different WebVR cameras available.
  20643. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20644. */
  20645. Camera.prototype._getWebVRViewMatrix = function () {
  20646. return BABYLON.Matrix.Identity();
  20647. };
  20648. Camera.prototype.setCameraRigParameter = function (name, value) {
  20649. if (!this._cameraRigParams) {
  20650. this._cameraRigParams = {};
  20651. }
  20652. this._cameraRigParams[name] = value;
  20653. //provisionnally:
  20654. if (name === "interaxialDistance") {
  20655. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20656. }
  20657. };
  20658. /**
  20659. * needs to be overridden by children so sub has required properties to be copied
  20660. */
  20661. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20662. return null;
  20663. };
  20664. /**
  20665. * May need to be overridden by children
  20666. */
  20667. Camera.prototype._updateRigCameras = function () {
  20668. for (var i = 0; i < this._rigCameras.length; i++) {
  20669. this._rigCameras[i].minZ = this.minZ;
  20670. this._rigCameras[i].maxZ = this.maxZ;
  20671. this._rigCameras[i].fov = this.fov;
  20672. }
  20673. // only update viewport when ANAGLYPH
  20674. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20675. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20676. }
  20677. };
  20678. Camera.prototype._setupInputs = function () {
  20679. };
  20680. Camera.prototype.serialize = function () {
  20681. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20682. // Type
  20683. serializationObject.type = this.getClassName();
  20684. // Parent
  20685. if (this.parent) {
  20686. serializationObject.parentId = this.parent.id;
  20687. }
  20688. if (this.inputs) {
  20689. this.inputs.serialize(serializationObject);
  20690. }
  20691. // Animations
  20692. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20693. serializationObject.ranges = this.serializeAnimationRanges();
  20694. return serializationObject;
  20695. };
  20696. Camera.prototype.clone = function (name) {
  20697. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20698. };
  20699. Camera.prototype.getDirection = function (localAxis) {
  20700. var result = BABYLON.Vector3.Zero();
  20701. this.getDirectionToRef(localAxis, result);
  20702. return result;
  20703. };
  20704. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20705. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20706. };
  20707. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20708. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20709. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20710. switch (type) {
  20711. case "ArcRotateCamera":
  20712. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20713. case "DeviceOrientationCamera":
  20714. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20715. case "FollowCamera":
  20716. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20717. case "ArcFollowCamera":
  20718. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20719. case "GamepadCamera":
  20720. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20721. case "TouchCamera":
  20722. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20723. case "VirtualJoysticksCamera":
  20724. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20725. case "WebVRFreeCamera":
  20726. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20727. case "WebVRGamepadCamera":
  20728. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20729. case "VRDeviceOrientationFreeCamera":
  20730. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20731. case "VRDeviceOrientationGamepadCamera":
  20732. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20733. case "AnaglyphArcRotateCamera":
  20734. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20735. case "AnaglyphFreeCamera":
  20736. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20737. case "AnaglyphGamepadCamera":
  20738. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20739. case "AnaglyphUniversalCamera":
  20740. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20741. case "StereoscopicArcRotateCamera":
  20742. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20743. case "StereoscopicFreeCamera":
  20744. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20745. case "StereoscopicGamepadCamera":
  20746. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20747. case "StereoscopicUniversalCamera":
  20748. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20749. case "FreeCamera":// Forcing Universal here
  20750. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20751. default:// Universal Camera is the default value
  20752. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20753. }
  20754. };
  20755. Camera.prototype.computeWorldMatrix = function () {
  20756. return this.getWorldMatrix();
  20757. };
  20758. Camera.Parse = function (parsedCamera, scene) {
  20759. var type = parsedCamera.type;
  20760. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20761. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20762. // Parent
  20763. if (parsedCamera.parentId) {
  20764. camera._waitingParentId = parsedCamera.parentId;
  20765. }
  20766. //If camera has an input manager, let it parse inputs settings
  20767. if (camera.inputs) {
  20768. camera.inputs.parse(parsedCamera);
  20769. camera._setupInputs();
  20770. }
  20771. if (camera.setPosition) {
  20772. camera.position.copyFromFloats(0, 0, 0);
  20773. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20774. }
  20775. // Target
  20776. if (parsedCamera.target) {
  20777. if (camera.setTarget) {
  20778. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20779. }
  20780. }
  20781. // Apply 3d rig, when found
  20782. if (parsedCamera.cameraRigMode) {
  20783. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20784. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20785. }
  20786. // Animations
  20787. if (parsedCamera.animations) {
  20788. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20789. var parsedAnimation = parsedCamera.animations[animationIndex];
  20790. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20791. }
  20792. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20793. }
  20794. if (parsedCamera.autoAnimate) {
  20795. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20796. }
  20797. return camera;
  20798. };
  20799. // Statics
  20800. Camera._PERSPECTIVE_CAMERA = 0;
  20801. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20802. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20803. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20804. Camera._RIG_MODE_NONE = 0;
  20805. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20806. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20807. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20808. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20809. Camera._RIG_MODE_VR = 20;
  20810. Camera._RIG_MODE_WEBVR = 21;
  20811. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20812. Camera.UseAlternateWebVRRendering = false;
  20813. __decorate([
  20814. BABYLON.serializeAsVector3()
  20815. ], Camera.prototype, "position", void 0);
  20816. __decorate([
  20817. BABYLON.serializeAsVector3()
  20818. ], Camera.prototype, "upVector", void 0);
  20819. __decorate([
  20820. BABYLON.serialize()
  20821. ], Camera.prototype, "orthoLeft", void 0);
  20822. __decorate([
  20823. BABYLON.serialize()
  20824. ], Camera.prototype, "orthoRight", void 0);
  20825. __decorate([
  20826. BABYLON.serialize()
  20827. ], Camera.prototype, "orthoBottom", void 0);
  20828. __decorate([
  20829. BABYLON.serialize()
  20830. ], Camera.prototype, "orthoTop", void 0);
  20831. __decorate([
  20832. BABYLON.serialize()
  20833. ], Camera.prototype, "fov", void 0);
  20834. __decorate([
  20835. BABYLON.serialize()
  20836. ], Camera.prototype, "minZ", void 0);
  20837. __decorate([
  20838. BABYLON.serialize()
  20839. ], Camera.prototype, "maxZ", void 0);
  20840. __decorate([
  20841. BABYLON.serialize()
  20842. ], Camera.prototype, "inertia", void 0);
  20843. __decorate([
  20844. BABYLON.serialize()
  20845. ], Camera.prototype, "mode", void 0);
  20846. __decorate([
  20847. BABYLON.serialize()
  20848. ], Camera.prototype, "layerMask", void 0);
  20849. __decorate([
  20850. BABYLON.serialize()
  20851. ], Camera.prototype, "fovMode", void 0);
  20852. __decorate([
  20853. BABYLON.serialize()
  20854. ], Camera.prototype, "cameraRigMode", void 0);
  20855. __decorate([
  20856. BABYLON.serialize()
  20857. ], Camera.prototype, "interaxialDistance", void 0);
  20858. __decorate([
  20859. BABYLON.serialize()
  20860. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20861. return Camera;
  20862. }(BABYLON.Node));
  20863. BABYLON.Camera = Camera;
  20864. })(BABYLON || (BABYLON = {}));
  20865. //# sourceMappingURL=babylon.camera.js.map
  20866. var BABYLON;
  20867. (function (BABYLON) {
  20868. var RenderingManager = /** @class */ (function () {
  20869. function RenderingManager(scene) {
  20870. this._renderingGroups = new Array();
  20871. this._autoClearDepthStencil = {};
  20872. this._customOpaqueSortCompareFn = {};
  20873. this._customAlphaTestSortCompareFn = {};
  20874. this._customTransparentSortCompareFn = {};
  20875. this._renderinGroupInfo = null;
  20876. this._scene = scene;
  20877. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20878. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20879. }
  20880. }
  20881. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20882. if (depth === void 0) { depth = true; }
  20883. if (stencil === void 0) { stencil = true; }
  20884. if (this._depthStencilBufferAlreadyCleaned) {
  20885. return;
  20886. }
  20887. this._scene.getEngine().clear(null, false, depth, stencil);
  20888. this._depthStencilBufferAlreadyCleaned = true;
  20889. };
  20890. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20891. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20892. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20893. var info = null;
  20894. if (observable) {
  20895. if (!this._renderinGroupInfo) {
  20896. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20897. }
  20898. info = this._renderinGroupInfo;
  20899. info.scene = this._scene;
  20900. info.camera = this._scene.activeCamera;
  20901. }
  20902. // Dispatch sprites
  20903. if (renderSprites) {
  20904. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20905. var manager = this._scene.spriteManagers[index];
  20906. this.dispatchSprites(manager);
  20907. }
  20908. }
  20909. // Render
  20910. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20911. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20912. var renderingGroup = this._renderingGroups[index];
  20913. if (!renderingGroup && !observable)
  20914. continue;
  20915. var renderingGroupMask = 0;
  20916. // Fire PRECLEAR stage
  20917. if (observable && info) {
  20918. renderingGroupMask = Math.pow(2, index);
  20919. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20920. info.renderingGroupId = index;
  20921. observable.notifyObservers(info, renderingGroupMask);
  20922. }
  20923. // Clear depth/stencil if needed
  20924. if (RenderingManager.AUTOCLEAR) {
  20925. var autoClear = this._autoClearDepthStencil[index];
  20926. if (autoClear && autoClear.autoClear) {
  20927. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20928. }
  20929. }
  20930. if (observable && info) {
  20931. // Fire PREOPAQUE stage
  20932. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20933. observable.notifyObservers(info, renderingGroupMask);
  20934. // Fire PRETRANSPARENT stage
  20935. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20936. observable.notifyObservers(info, renderingGroupMask);
  20937. }
  20938. if (renderingGroup)
  20939. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20940. // Fire POSTTRANSPARENT stage
  20941. if (observable && info) {
  20942. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20943. observable.notifyObservers(info, renderingGroupMask);
  20944. }
  20945. }
  20946. };
  20947. RenderingManager.prototype.reset = function () {
  20948. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20949. var renderingGroup = this._renderingGroups[index];
  20950. if (renderingGroup) {
  20951. renderingGroup.prepare();
  20952. }
  20953. }
  20954. };
  20955. RenderingManager.prototype.dispose = function () {
  20956. this.freeRenderingGroups();
  20957. this._renderingGroups.length = 0;
  20958. };
  20959. /**
  20960. * Clear the info related to rendering groups preventing retention points during dispose.
  20961. */
  20962. RenderingManager.prototype.freeRenderingGroups = function () {
  20963. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20964. var renderingGroup = this._renderingGroups[index];
  20965. if (renderingGroup) {
  20966. renderingGroup.dispose();
  20967. }
  20968. }
  20969. };
  20970. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20971. if (this._renderingGroups[renderingGroupId] === undefined) {
  20972. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20973. }
  20974. };
  20975. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20976. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20977. this._prepareRenderingGroup(renderingGroupId);
  20978. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20979. };
  20980. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  20981. var renderingGroupId = particleSystem.renderingGroupId || 0;
  20982. this._prepareRenderingGroup(renderingGroupId);
  20983. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  20984. };
  20985. /**
  20986. * @param subMesh The submesh to dispatch
  20987. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20988. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20989. */
  20990. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  20991. if (mesh === undefined) {
  20992. mesh = subMesh.getMesh();
  20993. }
  20994. var renderingGroupId = mesh.renderingGroupId || 0;
  20995. this._prepareRenderingGroup(renderingGroupId);
  20996. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  20997. };
  20998. /**
  20999. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  21000. * This allowed control for front to back rendering or reversly depending of the special needs.
  21001. *
  21002. * @param renderingGroupId The rendering group id corresponding to its index
  21003. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  21004. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  21005. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  21006. */
  21007. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21008. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21009. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21010. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21011. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  21012. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  21013. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  21014. if (this._renderingGroups[renderingGroupId]) {
  21015. var group = this._renderingGroups[renderingGroupId];
  21016. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  21017. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  21018. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  21019. }
  21020. };
  21021. /**
  21022. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  21023. *
  21024. * @param renderingGroupId The rendering group id corresponding to its index
  21025. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  21026. * @param depth Automatically clears depth between groups if true and autoClear is true.
  21027. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  21028. */
  21029. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  21030. if (depth === void 0) { depth = true; }
  21031. if (stencil === void 0) { stencil = true; }
  21032. this._autoClearDepthStencil[renderingGroupId] = {
  21033. autoClear: autoClearDepthStencil,
  21034. depth: depth,
  21035. stencil: stencil
  21036. };
  21037. };
  21038. /**
  21039. * The max id used for rendering groups (not included)
  21040. */
  21041. RenderingManager.MAX_RENDERINGGROUPS = 4;
  21042. /**
  21043. * The min id used for rendering groups (included)
  21044. */
  21045. RenderingManager.MIN_RENDERINGGROUPS = 0;
  21046. /**
  21047. * Used to globally prevent autoclearing scenes.
  21048. */
  21049. RenderingManager.AUTOCLEAR = true;
  21050. return RenderingManager;
  21051. }());
  21052. BABYLON.RenderingManager = RenderingManager;
  21053. })(BABYLON || (BABYLON = {}));
  21054. //# sourceMappingURL=babylon.renderingManager.js.map
  21055. var BABYLON;
  21056. (function (BABYLON) {
  21057. var RenderingGroup = /** @class */ (function () {
  21058. /**
  21059. * Creates a new rendering group.
  21060. * @param index The rendering group index
  21061. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  21062. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  21063. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  21064. */
  21065. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21066. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21067. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21068. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21069. this.index = index;
  21070. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  21071. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  21072. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  21073. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  21074. this._particleSystems = new BABYLON.SmartArray(256);
  21075. this._spriteManagers = new BABYLON.SmartArray(256);
  21076. this._edgesRenderers = new BABYLON.SmartArray(16);
  21077. this._scene = scene;
  21078. this.opaqueSortCompareFn = opaqueSortCompareFn;
  21079. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  21080. this.transparentSortCompareFn = transparentSortCompareFn;
  21081. }
  21082. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  21083. /**
  21084. * Set the opaque sort comparison function.
  21085. * If null the sub meshes will be render in the order they were created
  21086. */
  21087. set: function (value) {
  21088. this._opaqueSortCompareFn = value;
  21089. if (value) {
  21090. this._renderOpaque = this.renderOpaqueSorted;
  21091. }
  21092. else {
  21093. this._renderOpaque = RenderingGroup.renderUnsorted;
  21094. }
  21095. },
  21096. enumerable: true,
  21097. configurable: true
  21098. });
  21099. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  21100. /**
  21101. * Set the alpha test sort comparison function.
  21102. * If null the sub meshes will be render in the order they were created
  21103. */
  21104. set: function (value) {
  21105. this._alphaTestSortCompareFn = value;
  21106. if (value) {
  21107. this._renderAlphaTest = this.renderAlphaTestSorted;
  21108. }
  21109. else {
  21110. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  21111. }
  21112. },
  21113. enumerable: true,
  21114. configurable: true
  21115. });
  21116. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  21117. /**
  21118. * Set the transparent sort comparison function.
  21119. * If null the sub meshes will be render in the order they were created
  21120. */
  21121. set: function (value) {
  21122. if (value) {
  21123. this._transparentSortCompareFn = value;
  21124. }
  21125. else {
  21126. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  21127. }
  21128. this._renderTransparent = this.renderTransparentSorted;
  21129. },
  21130. enumerable: true,
  21131. configurable: true
  21132. });
  21133. /**
  21134. * Render all the sub meshes contained in the group.
  21135. * @param customRenderFunction Used to override the default render behaviour of the group.
  21136. * @returns true if rendered some submeshes.
  21137. */
  21138. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  21139. if (customRenderFunction) {
  21140. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  21141. return;
  21142. }
  21143. var engine = this._scene.getEngine();
  21144. // Depth only
  21145. if (this._depthOnlySubMeshes.length !== 0) {
  21146. engine.setColorWrite(false);
  21147. this._renderAlphaTest(this._depthOnlySubMeshes);
  21148. engine.setColorWrite(true);
  21149. }
  21150. // Opaque
  21151. if (this._opaqueSubMeshes.length !== 0) {
  21152. this._renderOpaque(this._opaqueSubMeshes);
  21153. }
  21154. // Alpha test
  21155. if (this._alphaTestSubMeshes.length !== 0) {
  21156. this._renderAlphaTest(this._alphaTestSubMeshes);
  21157. }
  21158. var stencilState = engine.getStencilBuffer();
  21159. engine.setStencilBuffer(false);
  21160. // Sprites
  21161. if (renderSprites) {
  21162. this._renderSprites();
  21163. }
  21164. // Particles
  21165. if (renderParticles) {
  21166. this._renderParticles(activeMeshes);
  21167. }
  21168. if (this.onBeforeTransparentRendering) {
  21169. this.onBeforeTransparentRendering();
  21170. }
  21171. // Transparent
  21172. if (this._transparentSubMeshes.length !== 0) {
  21173. this._renderTransparent(this._transparentSubMeshes);
  21174. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21175. }
  21176. // Set back stencil to false in case it changes before the edge renderer.
  21177. engine.setStencilBuffer(false);
  21178. // Edges
  21179. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  21180. this._edgesRenderers.data[edgesRendererIndex].render();
  21181. }
  21182. // Restore Stencil state.
  21183. engine.setStencilBuffer(stencilState);
  21184. };
  21185. /**
  21186. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  21187. * @param subMeshes The submeshes to render
  21188. */
  21189. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  21190. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  21191. };
  21192. /**
  21193. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  21194. * @param subMeshes The submeshes to render
  21195. */
  21196. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  21197. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  21198. };
  21199. /**
  21200. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  21201. * @param subMeshes The submeshes to render
  21202. */
  21203. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  21204. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  21205. };
  21206. /**
  21207. * Renders the submeshes in a specified order.
  21208. * @param subMeshes The submeshes to sort before render
  21209. * @param sortCompareFn The comparison function use to sort
  21210. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  21211. * @param transparent Specifies to activate blending if true
  21212. */
  21213. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  21214. var subIndex = 0;
  21215. var subMesh;
  21216. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  21217. for (; subIndex < subMeshes.length; subIndex++) {
  21218. subMesh = subMeshes.data[subIndex];
  21219. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  21220. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  21221. }
  21222. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  21223. if (sortCompareFn) {
  21224. sortedArray.sort(sortCompareFn);
  21225. }
  21226. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  21227. subMesh = sortedArray[subIndex];
  21228. if (transparent) {
  21229. var material = subMesh.getMaterial();
  21230. if (material && material.needDepthPrePass) {
  21231. var engine = material.getScene().getEngine();
  21232. engine.setColorWrite(false);
  21233. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21234. subMesh.render(false);
  21235. engine.setColorWrite(true);
  21236. }
  21237. }
  21238. subMesh.render(transparent);
  21239. }
  21240. };
  21241. /**
  21242. * Renders the submeshes in the order they were dispatched (no sort applied).
  21243. * @param subMeshes The submeshes to render
  21244. */
  21245. RenderingGroup.renderUnsorted = function (subMeshes) {
  21246. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  21247. var submesh = subMeshes.data[subIndex];
  21248. submesh.render(false);
  21249. }
  21250. };
  21251. /**
  21252. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21253. * are rendered back to front if in the same alpha index.
  21254. *
  21255. * @param a The first submesh
  21256. * @param b The second submesh
  21257. * @returns The result of the comparison
  21258. */
  21259. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  21260. // Alpha index first
  21261. if (a._alphaIndex > b._alphaIndex) {
  21262. return 1;
  21263. }
  21264. if (a._alphaIndex < b._alphaIndex) {
  21265. return -1;
  21266. }
  21267. // Then distance to camera
  21268. return RenderingGroup.backToFrontSortCompare(a, b);
  21269. };
  21270. /**
  21271. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21272. * are rendered back to front.
  21273. *
  21274. * @param a The first submesh
  21275. * @param b The second submesh
  21276. * @returns The result of the comparison
  21277. */
  21278. RenderingGroup.backToFrontSortCompare = function (a, b) {
  21279. // Then distance to camera
  21280. if (a._distanceToCamera < b._distanceToCamera) {
  21281. return 1;
  21282. }
  21283. if (a._distanceToCamera > b._distanceToCamera) {
  21284. return -1;
  21285. }
  21286. return 0;
  21287. };
  21288. /**
  21289. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21290. * are rendered front to back (prevent overdraw).
  21291. *
  21292. * @param a The first submesh
  21293. * @param b The second submesh
  21294. * @returns The result of the comparison
  21295. */
  21296. RenderingGroup.frontToBackSortCompare = function (a, b) {
  21297. // Then distance to camera
  21298. if (a._distanceToCamera < b._distanceToCamera) {
  21299. return -1;
  21300. }
  21301. if (a._distanceToCamera > b._distanceToCamera) {
  21302. return 1;
  21303. }
  21304. return 0;
  21305. };
  21306. /**
  21307. * Resets the different lists of submeshes to prepare a new frame.
  21308. */
  21309. RenderingGroup.prototype.prepare = function () {
  21310. this._opaqueSubMeshes.reset();
  21311. this._transparentSubMeshes.reset();
  21312. this._alphaTestSubMeshes.reset();
  21313. this._depthOnlySubMeshes.reset();
  21314. this._particleSystems.reset();
  21315. this._spriteManagers.reset();
  21316. this._edgesRenderers.reset();
  21317. };
  21318. RenderingGroup.prototype.dispose = function () {
  21319. this._opaqueSubMeshes.dispose();
  21320. this._transparentSubMeshes.dispose();
  21321. this._alphaTestSubMeshes.dispose();
  21322. this._depthOnlySubMeshes.dispose();
  21323. this._particleSystems.dispose();
  21324. this._spriteManagers.dispose();
  21325. this._edgesRenderers.dispose();
  21326. };
  21327. /**
  21328. * Inserts the submesh in its correct queue depending on its material.
  21329. * @param subMesh The submesh to dispatch
  21330. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21331. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21332. */
  21333. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  21334. // Get mesh and materials if not provided
  21335. if (mesh === undefined) {
  21336. mesh = subMesh.getMesh();
  21337. }
  21338. if (material === undefined) {
  21339. material = subMesh.getMaterial();
  21340. }
  21341. if (material === null || material === undefined) {
  21342. return;
  21343. }
  21344. if (material.needAlphaBlendingForMesh(mesh)) {
  21345. this._transparentSubMeshes.push(subMesh);
  21346. }
  21347. else if (material.needAlphaTesting()) {
  21348. if (material.needDepthPrePass) {
  21349. this._depthOnlySubMeshes.push(subMesh);
  21350. }
  21351. this._alphaTestSubMeshes.push(subMesh);
  21352. }
  21353. else {
  21354. if (material.needDepthPrePass) {
  21355. this._depthOnlySubMeshes.push(subMesh);
  21356. }
  21357. this._opaqueSubMeshes.push(subMesh); // Opaque
  21358. }
  21359. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21360. this._edgesRenderers.push(mesh._edgesRenderer);
  21361. }
  21362. };
  21363. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21364. this._spriteManagers.push(spriteManager);
  21365. };
  21366. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21367. this._particleSystems.push(particleSystem);
  21368. };
  21369. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21370. if (this._particleSystems.length === 0) {
  21371. return;
  21372. }
  21373. // Particles
  21374. var activeCamera = this._scene.activeCamera;
  21375. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21376. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21377. var particleSystem = this._particleSystems.data[particleIndex];
  21378. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21379. continue;
  21380. }
  21381. var emitter = particleSystem.emitter;
  21382. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21383. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21384. }
  21385. }
  21386. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21387. };
  21388. RenderingGroup.prototype._renderSprites = function () {
  21389. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21390. return;
  21391. }
  21392. // Sprites
  21393. var activeCamera = this._scene.activeCamera;
  21394. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21395. for (var id = 0; id < this._spriteManagers.length; id++) {
  21396. var spriteManager = this._spriteManagers.data[id];
  21397. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21398. spriteManager.render();
  21399. }
  21400. }
  21401. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21402. };
  21403. return RenderingGroup;
  21404. }());
  21405. BABYLON.RenderingGroup = RenderingGroup;
  21406. })(BABYLON || (BABYLON = {}));
  21407. //# sourceMappingURL=babylon.renderingGroup.js.map
  21408. var BABYLON;
  21409. (function (BABYLON) {
  21410. var ClickInfo = /** @class */ (function () {
  21411. function ClickInfo() {
  21412. this._singleClick = false;
  21413. this._doubleClick = false;
  21414. this._hasSwiped = false;
  21415. this._ignore = false;
  21416. }
  21417. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21418. get: function () {
  21419. return this._singleClick;
  21420. },
  21421. set: function (b) {
  21422. this._singleClick = b;
  21423. },
  21424. enumerable: true,
  21425. configurable: true
  21426. });
  21427. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21428. get: function () {
  21429. return this._doubleClick;
  21430. },
  21431. set: function (b) {
  21432. this._doubleClick = b;
  21433. },
  21434. enumerable: true,
  21435. configurable: true
  21436. });
  21437. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21438. get: function () {
  21439. return this._hasSwiped;
  21440. },
  21441. set: function (b) {
  21442. this._hasSwiped = b;
  21443. },
  21444. enumerable: true,
  21445. configurable: true
  21446. });
  21447. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21448. get: function () {
  21449. return this._ignore;
  21450. },
  21451. set: function (b) {
  21452. this._ignore = b;
  21453. },
  21454. enumerable: true,
  21455. configurable: true
  21456. });
  21457. return ClickInfo;
  21458. }());
  21459. /**
  21460. * This class is used by the onRenderingGroupObservable
  21461. */
  21462. var RenderingGroupInfo = /** @class */ (function () {
  21463. function RenderingGroupInfo() {
  21464. }
  21465. /**
  21466. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21467. * This stage will be fired no matter what
  21468. */
  21469. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21470. /**
  21471. * Called before opaque object are rendered.
  21472. * This stage will be fired only if there's 3D Opaque content to render
  21473. */
  21474. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21475. /**
  21476. * Called after the opaque objects are rendered and before the transparent ones
  21477. * This stage will be fired only if there's 3D transparent content to render
  21478. */
  21479. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21480. /**
  21481. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21482. * This stage will be fired no matter what
  21483. */
  21484. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21485. return RenderingGroupInfo;
  21486. }());
  21487. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21488. /**
  21489. * Represents a scene to be rendered by the engine.
  21490. * @see http://doc.babylonjs.com/page.php?p=21911
  21491. */
  21492. var Scene = /** @class */ (function () {
  21493. /**
  21494. * @constructor
  21495. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21496. */
  21497. function Scene(engine) {
  21498. // Members
  21499. this.autoClear = true;
  21500. this.autoClearDepthAndStencil = true;
  21501. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21502. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21503. this.forceWireframe = false;
  21504. this._forcePointsCloud = false;
  21505. this.forceShowBoundingBoxes = false;
  21506. this.animationsEnabled = true;
  21507. this.useConstantAnimationDeltaTime = false;
  21508. this.constantlyUpdateMeshUnderPointer = false;
  21509. this.hoverCursor = "pointer";
  21510. this.defaultCursor = "";
  21511. /**
  21512. * This is used to call preventDefault() on pointer down
  21513. * in order to block unwanted artifacts like system double clicks
  21514. */
  21515. this.preventDefaultOnPointerDown = true;
  21516. // Metadata
  21517. this.metadata = null;
  21518. /**
  21519. * An event triggered when the scene is disposed.
  21520. * @type {BABYLON.Observable}
  21521. */
  21522. this.onDisposeObservable = new BABYLON.Observable();
  21523. /**
  21524. * An event triggered before rendering the scene (right after animations and physics)
  21525. * @type {BABYLON.Observable}
  21526. */
  21527. this.onBeforeRenderObservable = new BABYLON.Observable();
  21528. /**
  21529. * An event triggered after rendering the scene
  21530. * @type {BABYLON.Observable}
  21531. */
  21532. this.onAfterRenderObservable = new BABYLON.Observable();
  21533. /**
  21534. * An event triggered before animating the scene
  21535. * @type {BABYLON.Observable}
  21536. */
  21537. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21538. /**
  21539. * An event triggered after animations processing
  21540. * @type {BABYLON.Observable}
  21541. */
  21542. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21543. /**
  21544. * An event triggered before draw calls are ready to be sent
  21545. * @type {BABYLON.Observable}
  21546. */
  21547. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21548. /**
  21549. * An event triggered after draw calls have been sent
  21550. * @type {BABYLON.Observable}
  21551. */
  21552. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21553. /**
  21554. * An event triggered when physic simulation is about to be run
  21555. * @type {BABYLON.Observable}
  21556. */
  21557. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21558. /**
  21559. * An event triggered when physic simulation has been done
  21560. * @type {BABYLON.Observable}
  21561. */
  21562. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21563. /**
  21564. * An event triggered when the scene is ready
  21565. * @type {BABYLON.Observable}
  21566. */
  21567. this.onReadyObservable = new BABYLON.Observable();
  21568. /**
  21569. * An event triggered before rendering a camera
  21570. * @type {BABYLON.Observable}
  21571. */
  21572. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21573. /**
  21574. * An event triggered after rendering a camera
  21575. * @type {BABYLON.Observable}
  21576. */
  21577. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21578. /**
  21579. * An event triggered when active meshes evaluation is about to start
  21580. * @type {BABYLON.Observable}
  21581. */
  21582. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21583. /**
  21584. * An event triggered when active meshes evaluation is done
  21585. * @type {BABYLON.Observable}
  21586. */
  21587. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21588. /**
  21589. * An event triggered when particles rendering is about to start
  21590. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21591. * @type {BABYLON.Observable}
  21592. */
  21593. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21594. /**
  21595. * An event triggered when particles rendering is done
  21596. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21597. * @type {BABYLON.Observable}
  21598. */
  21599. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21600. /**
  21601. * An event triggered when sprites rendering is about to start
  21602. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21603. * @type {BABYLON.Observable}
  21604. */
  21605. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21606. /**
  21607. * An event triggered when sprites rendering is done
  21608. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21609. * @type {BABYLON.Observable}
  21610. */
  21611. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21612. /**
  21613. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21614. * @type {BABYLON.Observable}
  21615. */
  21616. this.onDataLoadedObservable = new BABYLON.Observable();
  21617. /**
  21618. * An event triggered when a camera is created
  21619. * @type {BABYLON.Observable}
  21620. */
  21621. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21622. /**
  21623. * An event triggered when a camera is removed
  21624. * @type {BABYLON.Observable}
  21625. */
  21626. this.onCameraRemovedObservable = new BABYLON.Observable();
  21627. /**
  21628. * An event triggered when a light is created
  21629. * @type {BABYLON.Observable}
  21630. */
  21631. this.onNewLightAddedObservable = new BABYLON.Observable();
  21632. /**
  21633. * An event triggered when a light is removed
  21634. * @type {BABYLON.Observable}
  21635. */
  21636. this.onLightRemovedObservable = new BABYLON.Observable();
  21637. /**
  21638. * An event triggered when a geometry is created
  21639. * @type {BABYLON.Observable}
  21640. */
  21641. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21642. /**
  21643. * An event triggered when a geometry is removed
  21644. * @type {BABYLON.Observable}
  21645. */
  21646. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21647. /**
  21648. * An event triggered when a transform node is created
  21649. * @type {BABYLON.Observable}
  21650. */
  21651. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21652. /**
  21653. * An event triggered when a transform node is removed
  21654. * @type {BABYLON.Observable}
  21655. */
  21656. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21657. /**
  21658. * An event triggered when a mesh is created
  21659. * @type {BABYLON.Observable}
  21660. */
  21661. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21662. /**
  21663. * An event triggered when a mesh is removed
  21664. * @type {BABYLON.Observable}
  21665. */
  21666. this.onMeshRemovedObservable = new BABYLON.Observable();
  21667. /**
  21668. * An event triggered when render targets are about to be rendered
  21669. * Can happen multiple times per frame.
  21670. * @type {BABYLON.Observable}
  21671. */
  21672. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21673. /**
  21674. * An event triggered when render targets were rendered.
  21675. * Can happen multiple times per frame.
  21676. * @type {BABYLON.Observable}
  21677. */
  21678. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21679. /**
  21680. * An event triggered before calculating deterministic simulation step
  21681. * @type {BABYLON.Observable}
  21682. */
  21683. this.onBeforeStepObservable = new BABYLON.Observable();
  21684. /**
  21685. * An event triggered after calculating deterministic simulation step
  21686. * @type {BABYLON.Observable}
  21687. */
  21688. this.onAfterStepObservable = new BABYLON.Observable();
  21689. /**
  21690. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21691. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21692. * 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)
  21693. */
  21694. this.onRenderingGroupObservable = new BABYLON.Observable();
  21695. // Animations
  21696. this.animations = [];
  21697. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  21698. /**
  21699. * 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).
  21700. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21701. */
  21702. this.onPrePointerObservable = new BABYLON.Observable();
  21703. /**
  21704. * Observable event triggered each time an input event is received from the rendering canvas
  21705. */
  21706. this.onPointerObservable = new BABYLON.Observable();
  21707. this._meshPickProceed = false;
  21708. this._currentPickResult = null;
  21709. this._previousPickResult = null;
  21710. this._totalPointersPressed = 0;
  21711. this._doubleClickOccured = false;
  21712. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21713. this.cameraToUseForPointers = null;
  21714. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21715. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21716. this._startingPointerTime = 0;
  21717. this._previousStartingPointerTime = 0;
  21718. // Deterministic lockstep
  21719. this._timeAccumulator = 0;
  21720. this._currentStepId = 0;
  21721. this._currentInternalStep = 0;
  21722. // Keyboard
  21723. /**
  21724. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21725. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21726. */
  21727. this.onPreKeyboardObservable = new BABYLON.Observable();
  21728. /**
  21729. * Observable event triggered each time an keyboard event is received from the hosting window
  21730. */
  21731. this.onKeyboardObservable = new BABYLON.Observable();
  21732. // Coordinate system
  21733. /**
  21734. * use right-handed coordinate system on this scene.
  21735. * @type {boolean}
  21736. */
  21737. this._useRightHandedSystem = false;
  21738. // Fog
  21739. this._fogEnabled = true;
  21740. this._fogMode = Scene.FOGMODE_NONE;
  21741. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21742. this.fogDensity = 0.1;
  21743. this.fogStart = 0;
  21744. this.fogEnd = 1000.0;
  21745. // Lights
  21746. /**
  21747. * is shadow enabled on this scene.
  21748. * @type {boolean}
  21749. */
  21750. this._shadowsEnabled = true;
  21751. /**
  21752. * is light enabled on this scene.
  21753. * @type {boolean}
  21754. */
  21755. this._lightsEnabled = true;
  21756. /**
  21757. * All of the lights added to this scene.
  21758. * @see BABYLON.Light
  21759. * @type {BABYLON.Light[]}
  21760. */
  21761. this.lights = new Array();
  21762. // Cameras
  21763. /** All of the cameras added to this scene. */
  21764. this.cameras = new Array();
  21765. /** All of the active cameras added to this scene. */
  21766. this.activeCameras = new Array();
  21767. // Meshes
  21768. /**
  21769. * All of the tranform nodes added to this scene.
  21770. * @see BABYLON.TransformNode
  21771. * @type {BABYLON.TransformNode[]}
  21772. */
  21773. this.transformNodes = new Array();
  21774. /**
  21775. * All of the (abstract) meshes added to this scene.
  21776. * @see BABYLON.AbstractMesh
  21777. * @type {BABYLON.AbstractMesh[]}
  21778. */
  21779. this.meshes = new Array();
  21780. /**
  21781. * All of the animation groups added to this scene.
  21782. * @see BABYLON.AnimationGroup
  21783. * @type {BABYLON.AnimationGroup[]}
  21784. */
  21785. this.animationGroups = new Array();
  21786. // Geometries
  21787. this._geometries = new Array();
  21788. this.materials = new Array();
  21789. this.multiMaterials = new Array();
  21790. // Textures
  21791. this._texturesEnabled = true;
  21792. this.textures = new Array();
  21793. // Particles
  21794. this.particlesEnabled = true;
  21795. this.particleSystems = new Array();
  21796. // Sprites
  21797. this.spritesEnabled = true;
  21798. this.spriteManagers = new Array();
  21799. /**
  21800. * The list of layers (background and foreground) of the scene.
  21801. */
  21802. this.layers = new Array();
  21803. /**
  21804. * The list of effect layers (highlights/glow) contained in the scene.
  21805. */
  21806. this.effectLayers = new Array();
  21807. // Skeletons
  21808. this._skeletonsEnabled = true;
  21809. this.skeletons = new Array();
  21810. // Morph targets
  21811. this.morphTargetManagers = new Array();
  21812. // Lens flares
  21813. this.lensFlaresEnabled = true;
  21814. this.lensFlareSystems = new Array();
  21815. // Collisions
  21816. this.collisionsEnabled = true;
  21817. /** Defines the gravity applied to this scene */
  21818. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21819. // Postprocesses
  21820. this.postProcesses = new Array();
  21821. this.postProcessesEnabled = true;
  21822. // Customs render targets
  21823. this.renderTargetsEnabled = true;
  21824. this.dumpNextRenderTargets = false;
  21825. this.customRenderTargets = new Array();
  21826. // Imported meshes
  21827. this.importedMeshesFiles = new Array();
  21828. // Probes
  21829. this.probesEnabled = true;
  21830. this.reflectionProbes = new Array();
  21831. this._actionManagers = new Array();
  21832. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21833. // Procedural textures
  21834. this.proceduralTexturesEnabled = true;
  21835. this._proceduralTextures = new Array();
  21836. this.soundTracks = new Array();
  21837. this._audioEnabled = true;
  21838. this._headphone = false;
  21839. // Performance counters
  21840. this._totalVertices = new BABYLON.PerfCounter();
  21841. this._activeIndices = new BABYLON.PerfCounter();
  21842. this._activeParticles = new BABYLON.PerfCounter();
  21843. this._activeBones = new BABYLON.PerfCounter();
  21844. this._animationTime = 0;
  21845. this.animationTimeScale = 1;
  21846. this._renderId = 0;
  21847. this._executeWhenReadyTimeoutId = -1;
  21848. this._intermediateRendering = false;
  21849. this._viewUpdateFlag = -1;
  21850. this._projectionUpdateFlag = -1;
  21851. this._alternateViewUpdateFlag = -1;
  21852. this._alternateProjectionUpdateFlag = -1;
  21853. this._toBeDisposed = new BABYLON.SmartArray(256);
  21854. this._activeRequests = new Array();
  21855. this._pendingData = new Array();
  21856. this._isDisposed = false;
  21857. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21858. this._activeMeshes = new BABYLON.SmartArray(256);
  21859. this._processedMaterials = new BABYLON.SmartArray(256);
  21860. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21861. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21862. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21863. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21864. this._activeAnimatables = new Array();
  21865. this._transformMatrix = BABYLON.Matrix.Zero();
  21866. this._useAlternateCameraConfiguration = false;
  21867. this._alternateRendering = false;
  21868. this.requireLightSorting = false;
  21869. this._depthRenderer = {};
  21870. this._activeMeshesFrozen = false;
  21871. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21872. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21873. this._engine.scenes.push(this);
  21874. this._uid = null;
  21875. this._renderingManager = new BABYLON.RenderingManager(this);
  21876. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21877. if (BABYLON.OutlineRenderer) {
  21878. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21879. }
  21880. if (BABYLON.Tools.IsWindowObjectExist()) {
  21881. this.attachControl();
  21882. }
  21883. //simplification queue
  21884. if (BABYLON.SimplificationQueue) {
  21885. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21886. }
  21887. //collision coordinator initialization. For now legacy per default.
  21888. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21889. // Uniform Buffer
  21890. this._createUbo();
  21891. // Default Image processing definition.
  21892. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21893. }
  21894. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21895. /** The fog is deactivated */
  21896. get: function () {
  21897. return Scene._FOGMODE_NONE;
  21898. },
  21899. enumerable: true,
  21900. configurable: true
  21901. });
  21902. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21903. /** The fog density is following an exponential function */
  21904. get: function () {
  21905. return Scene._FOGMODE_EXP;
  21906. },
  21907. enumerable: true,
  21908. configurable: true
  21909. });
  21910. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21911. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21912. get: function () {
  21913. return Scene._FOGMODE_EXP2;
  21914. },
  21915. enumerable: true,
  21916. configurable: true
  21917. });
  21918. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21919. /** The fog density is following a linear function. */
  21920. get: function () {
  21921. return Scene._FOGMODE_LINEAR;
  21922. },
  21923. enumerable: true,
  21924. configurable: true
  21925. });
  21926. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21927. /**
  21928. * Texture used in all pbr material as the reflection texture.
  21929. * As in the majority of the scene they are the same (exception for multi room and so on),
  21930. * this is easier to reference from here than from all the materials.
  21931. */
  21932. get: function () {
  21933. return this._environmentTexture;
  21934. },
  21935. /**
  21936. * Texture used in all pbr material as the reflection texture.
  21937. * As in the majority of the scene they are the same (exception for multi room and so on),
  21938. * this is easier to set here than in all the materials.
  21939. */
  21940. set: function (value) {
  21941. if (this._environmentTexture === value) {
  21942. return;
  21943. }
  21944. this._environmentTexture = value;
  21945. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21946. },
  21947. enumerable: true,
  21948. configurable: true
  21949. });
  21950. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21951. /**
  21952. * Default image processing configuration used either in the rendering
  21953. * Forward main pass or through the imageProcessingPostProcess if present.
  21954. * As in the majority of the scene they are the same (exception for multi camera),
  21955. * this is easier to reference from here than from all the materials and post process.
  21956. *
  21957. * No setter as we it is a shared configuration, you can set the values instead.
  21958. */
  21959. get: function () {
  21960. return this._imageProcessingConfiguration;
  21961. },
  21962. enumerable: true,
  21963. configurable: true
  21964. });
  21965. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21966. get: function () {
  21967. return this._forcePointsCloud;
  21968. },
  21969. set: function (value) {
  21970. if (this._forcePointsCloud === value) {
  21971. return;
  21972. }
  21973. this._forcePointsCloud = value;
  21974. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21975. },
  21976. enumerable: true,
  21977. configurable: true
  21978. });
  21979. Object.defineProperty(Scene.prototype, "onDispose", {
  21980. /** A function to be executed when this scene is disposed. */
  21981. set: function (callback) {
  21982. if (this._onDisposeObserver) {
  21983. this.onDisposeObservable.remove(this._onDisposeObserver);
  21984. }
  21985. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21986. },
  21987. enumerable: true,
  21988. configurable: true
  21989. });
  21990. Object.defineProperty(Scene.prototype, "beforeRender", {
  21991. /** A function to be executed before rendering this scene */
  21992. set: function (callback) {
  21993. if (this._onBeforeRenderObserver) {
  21994. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21995. }
  21996. if (callback) {
  21997. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21998. }
  21999. },
  22000. enumerable: true,
  22001. configurable: true
  22002. });
  22003. Object.defineProperty(Scene.prototype, "afterRender", {
  22004. /** A function to be executed after rendering this scene */
  22005. set: function (callback) {
  22006. if (this._onAfterRenderObserver) {
  22007. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  22008. }
  22009. if (callback) {
  22010. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  22011. }
  22012. },
  22013. enumerable: true,
  22014. configurable: true
  22015. });
  22016. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  22017. set: function (callback) {
  22018. if (this._onBeforeCameraRenderObserver) {
  22019. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  22020. }
  22021. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  22022. },
  22023. enumerable: true,
  22024. configurable: true
  22025. });
  22026. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  22027. set: function (callback) {
  22028. if (this._onAfterCameraRenderObserver) {
  22029. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  22030. }
  22031. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  22032. },
  22033. enumerable: true,
  22034. configurable: true
  22035. });
  22036. Object.defineProperty(Scene.prototype, "gamepadManager", {
  22037. get: function () {
  22038. if (!this._gamepadManager) {
  22039. this._gamepadManager = new BABYLON.GamepadManager(this);
  22040. }
  22041. return this._gamepadManager;
  22042. },
  22043. enumerable: true,
  22044. configurable: true
  22045. });
  22046. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  22047. get: function () {
  22048. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  22049. },
  22050. enumerable: true,
  22051. configurable: true
  22052. });
  22053. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  22054. get: function () {
  22055. return this._useRightHandedSystem;
  22056. },
  22057. set: function (value) {
  22058. if (this._useRightHandedSystem === value) {
  22059. return;
  22060. }
  22061. this._useRightHandedSystem = value;
  22062. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22063. },
  22064. enumerable: true,
  22065. configurable: true
  22066. });
  22067. Scene.prototype.setStepId = function (newStepId) {
  22068. this._currentStepId = newStepId;
  22069. };
  22070. ;
  22071. Scene.prototype.getStepId = function () {
  22072. return this._currentStepId;
  22073. };
  22074. ;
  22075. Scene.prototype.getInternalStep = function () {
  22076. return this._currentInternalStep;
  22077. };
  22078. ;
  22079. Object.defineProperty(Scene.prototype, "fogEnabled", {
  22080. get: function () {
  22081. return this._fogEnabled;
  22082. },
  22083. /**
  22084. * is fog enabled on this scene.
  22085. */
  22086. set: function (value) {
  22087. if (this._fogEnabled === value) {
  22088. return;
  22089. }
  22090. this._fogEnabled = value;
  22091. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22092. },
  22093. enumerable: true,
  22094. configurable: true
  22095. });
  22096. Object.defineProperty(Scene.prototype, "fogMode", {
  22097. get: function () {
  22098. return this._fogMode;
  22099. },
  22100. set: function (value) {
  22101. if (this._fogMode === value) {
  22102. return;
  22103. }
  22104. this._fogMode = value;
  22105. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22106. },
  22107. enumerable: true,
  22108. configurable: true
  22109. });
  22110. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  22111. get: function () {
  22112. return this._shadowsEnabled;
  22113. },
  22114. set: function (value) {
  22115. if (this._shadowsEnabled === value) {
  22116. return;
  22117. }
  22118. this._shadowsEnabled = value;
  22119. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22120. },
  22121. enumerable: true,
  22122. configurable: true
  22123. });
  22124. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  22125. get: function () {
  22126. return this._lightsEnabled;
  22127. },
  22128. set: function (value) {
  22129. if (this._lightsEnabled === value) {
  22130. return;
  22131. }
  22132. this._lightsEnabled = value;
  22133. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22134. },
  22135. enumerable: true,
  22136. configurable: true
  22137. });
  22138. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  22139. /** The default material used on meshes when no material is affected */
  22140. get: function () {
  22141. if (!this._defaultMaterial) {
  22142. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  22143. }
  22144. return this._defaultMaterial;
  22145. },
  22146. /** The default material used on meshes when no material is affected */
  22147. set: function (value) {
  22148. this._defaultMaterial = value;
  22149. },
  22150. enumerable: true,
  22151. configurable: true
  22152. });
  22153. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  22154. get: function () {
  22155. return this._texturesEnabled;
  22156. },
  22157. set: function (value) {
  22158. if (this._texturesEnabled === value) {
  22159. return;
  22160. }
  22161. this._texturesEnabled = value;
  22162. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22163. },
  22164. enumerable: true,
  22165. configurable: true
  22166. });
  22167. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  22168. get: function () {
  22169. return this._skeletonsEnabled;
  22170. },
  22171. set: function (value) {
  22172. if (this._skeletonsEnabled === value) {
  22173. return;
  22174. }
  22175. this._skeletonsEnabled = value;
  22176. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  22177. },
  22178. enumerable: true,
  22179. configurable: true
  22180. });
  22181. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  22182. get: function () {
  22183. if (!this._postProcessRenderPipelineManager) {
  22184. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  22185. }
  22186. return this._postProcessRenderPipelineManager;
  22187. },
  22188. enumerable: true,
  22189. configurable: true
  22190. });
  22191. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  22192. get: function () {
  22193. if (!this._mainSoundTrack) {
  22194. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  22195. }
  22196. return this._mainSoundTrack;
  22197. },
  22198. enumerable: true,
  22199. configurable: true
  22200. });
  22201. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  22202. get: function () {
  22203. return this._alternateRendering;
  22204. },
  22205. enumerable: true,
  22206. configurable: true
  22207. });
  22208. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  22209. get: function () {
  22210. return this._frustumPlanes;
  22211. },
  22212. enumerable: true,
  22213. configurable: true
  22214. });
  22215. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  22216. /**
  22217. * Gets the current geometry buffer associated to the scene.
  22218. */
  22219. get: function () {
  22220. return this._geometryBufferRenderer;
  22221. },
  22222. /**
  22223. * Sets the current geometry buffer for the scene.
  22224. */
  22225. set: function (geometryBufferRenderer) {
  22226. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  22227. this._geometryBufferRenderer = geometryBufferRenderer;
  22228. }
  22229. },
  22230. enumerable: true,
  22231. configurable: true
  22232. });
  22233. Object.defineProperty(Scene.prototype, "debugLayer", {
  22234. // Properties
  22235. get: function () {
  22236. if (!this._debugLayer) {
  22237. this._debugLayer = new BABYLON.DebugLayer(this);
  22238. }
  22239. return this._debugLayer;
  22240. },
  22241. enumerable: true,
  22242. configurable: true
  22243. });
  22244. Object.defineProperty(Scene.prototype, "workerCollisions", {
  22245. get: function () {
  22246. return this._workerCollisions;
  22247. },
  22248. set: function (enabled) {
  22249. if (!BABYLON.CollisionCoordinatorLegacy) {
  22250. return;
  22251. }
  22252. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  22253. this._workerCollisions = enabled;
  22254. if (this.collisionCoordinator) {
  22255. this.collisionCoordinator.destroy();
  22256. }
  22257. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  22258. this.collisionCoordinator.init(this);
  22259. },
  22260. enumerable: true,
  22261. configurable: true
  22262. });
  22263. Object.defineProperty(Scene.prototype, "selectionOctree", {
  22264. get: function () {
  22265. return this._selectionOctree;
  22266. },
  22267. enumerable: true,
  22268. configurable: true
  22269. });
  22270. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  22271. /**
  22272. * The mesh that is currently under the pointer.
  22273. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  22274. */
  22275. get: function () {
  22276. return this._pointerOverMesh;
  22277. },
  22278. enumerable: true,
  22279. configurable: true
  22280. });
  22281. Object.defineProperty(Scene.prototype, "pointerX", {
  22282. /**
  22283. * Current on-screen X position of the pointer
  22284. * @return {number} X position of the pointer
  22285. */
  22286. get: function () {
  22287. return this._pointerX;
  22288. },
  22289. enumerable: true,
  22290. configurable: true
  22291. });
  22292. Object.defineProperty(Scene.prototype, "pointerY", {
  22293. /**
  22294. * Current on-screen Y position of the pointer
  22295. * @return {number} Y position of the pointer
  22296. */
  22297. get: function () {
  22298. return this._pointerY;
  22299. },
  22300. enumerable: true,
  22301. configurable: true
  22302. });
  22303. Scene.prototype.getCachedMaterial = function () {
  22304. return this._cachedMaterial;
  22305. };
  22306. Scene.prototype.getCachedEffect = function () {
  22307. return this._cachedEffect;
  22308. };
  22309. Scene.prototype.getCachedVisibility = function () {
  22310. return this._cachedVisibility;
  22311. };
  22312. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  22313. if (visibility === void 0) { visibility = 1; }
  22314. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  22315. };
  22316. Scene.prototype.getBoundingBoxRenderer = function () {
  22317. if (!this._boundingBoxRenderer) {
  22318. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  22319. }
  22320. return this._boundingBoxRenderer;
  22321. };
  22322. Scene.prototype.getOutlineRenderer = function () {
  22323. return this._outlineRenderer;
  22324. };
  22325. Scene.prototype.getEngine = function () {
  22326. return this._engine;
  22327. };
  22328. Scene.prototype.getTotalVertices = function () {
  22329. return this._totalVertices.current;
  22330. };
  22331. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  22332. get: function () {
  22333. return this._totalVertices;
  22334. },
  22335. enumerable: true,
  22336. configurable: true
  22337. });
  22338. Scene.prototype.getActiveIndices = function () {
  22339. return this._activeIndices.current;
  22340. };
  22341. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  22342. get: function () {
  22343. return this._activeIndices;
  22344. },
  22345. enumerable: true,
  22346. configurable: true
  22347. });
  22348. Scene.prototype.getActiveParticles = function () {
  22349. return this._activeParticles.current;
  22350. };
  22351. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22352. get: function () {
  22353. return this._activeParticles;
  22354. },
  22355. enumerable: true,
  22356. configurable: true
  22357. });
  22358. Scene.prototype.getActiveBones = function () {
  22359. return this._activeBones.current;
  22360. };
  22361. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22362. get: function () {
  22363. return this._activeBones;
  22364. },
  22365. enumerable: true,
  22366. configurable: true
  22367. });
  22368. // Stats
  22369. Scene.prototype.getInterFramePerfCounter = function () {
  22370. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22371. return 0;
  22372. };
  22373. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22374. get: function () {
  22375. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22376. return null;
  22377. },
  22378. enumerable: true,
  22379. configurable: true
  22380. });
  22381. Scene.prototype.getLastFrameDuration = function () {
  22382. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22383. return 0;
  22384. };
  22385. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22386. get: function () {
  22387. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22388. return null;
  22389. },
  22390. enumerable: true,
  22391. configurable: true
  22392. });
  22393. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22394. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22395. return 0;
  22396. };
  22397. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22398. get: function () {
  22399. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22400. return null;
  22401. },
  22402. enumerable: true,
  22403. configurable: true
  22404. });
  22405. Scene.prototype.getActiveMeshes = function () {
  22406. return this._activeMeshes;
  22407. };
  22408. Scene.prototype.getRenderTargetsDuration = function () {
  22409. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22410. return 0;
  22411. };
  22412. Scene.prototype.getRenderDuration = function () {
  22413. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22414. return 0;
  22415. };
  22416. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22417. get: function () {
  22418. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22419. return null;
  22420. },
  22421. enumerable: true,
  22422. configurable: true
  22423. });
  22424. Scene.prototype.getParticlesDuration = function () {
  22425. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22426. return 0;
  22427. };
  22428. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22429. get: function () {
  22430. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22431. return null;
  22432. },
  22433. enumerable: true,
  22434. configurable: true
  22435. });
  22436. Scene.prototype.getSpritesDuration = function () {
  22437. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22438. return 0;
  22439. };
  22440. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22441. get: function () {
  22442. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22443. return null;
  22444. },
  22445. enumerable: true,
  22446. configurable: true
  22447. });
  22448. Scene.prototype.getAnimationRatio = function () {
  22449. return this._animationRatio;
  22450. };
  22451. Scene.prototype.getRenderId = function () {
  22452. return this._renderId;
  22453. };
  22454. Scene.prototype.incrementRenderId = function () {
  22455. this._renderId++;
  22456. };
  22457. Scene.prototype._updatePointerPosition = function (evt) {
  22458. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22459. if (!canvasRect) {
  22460. return;
  22461. }
  22462. this._pointerX = evt.clientX - canvasRect.left;
  22463. this._pointerY = evt.clientY - canvasRect.top;
  22464. this._unTranslatedPointerX = this._pointerX;
  22465. this._unTranslatedPointerY = this._pointerY;
  22466. };
  22467. Scene.prototype._createUbo = function () {
  22468. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22469. this._sceneUbo.addUniform("viewProjection", 16);
  22470. this._sceneUbo.addUniform("view", 16);
  22471. };
  22472. Scene.prototype._createAlternateUbo = function () {
  22473. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22474. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22475. this._alternateSceneUbo.addUniform("view", 16);
  22476. };
  22477. // Pointers handling
  22478. /**
  22479. * Use this method to simulate a pointer move on a mesh
  22480. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22481. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22482. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22483. */
  22484. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22485. var evt = new PointerEvent("pointermove", pointerEventInit);
  22486. return this._processPointerMove(pickResult, evt);
  22487. };
  22488. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22489. var canvas = this._engine.getRenderingCanvas();
  22490. if (!canvas) {
  22491. return this;
  22492. }
  22493. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22494. this.setPointerOverSprite(null);
  22495. this.setPointerOverMesh(pickResult.pickedMesh);
  22496. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22497. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22498. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22499. }
  22500. else {
  22501. canvas.style.cursor = this.hoverCursor;
  22502. }
  22503. }
  22504. else {
  22505. canvas.style.cursor = this.defaultCursor;
  22506. }
  22507. }
  22508. else {
  22509. this.setPointerOverMesh(null);
  22510. // Sprites
  22511. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22512. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22513. this.setPointerOverSprite(pickResult.pickedSprite);
  22514. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22515. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22516. }
  22517. else {
  22518. canvas.style.cursor = this.hoverCursor;
  22519. }
  22520. }
  22521. else {
  22522. this.setPointerOverSprite(null);
  22523. // Restore pointer
  22524. canvas.style.cursor = this.defaultCursor;
  22525. }
  22526. }
  22527. if (pickResult) {
  22528. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22529. if (this.onPointerMove) {
  22530. this.onPointerMove(evt, pickResult, type);
  22531. }
  22532. if (this.onPointerObservable.hasObservers()) {
  22533. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22534. this.onPointerObservable.notifyObservers(pi, type);
  22535. }
  22536. }
  22537. return this;
  22538. };
  22539. /**
  22540. * Use this method to simulate a pointer down on a mesh
  22541. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22542. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22543. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22544. */
  22545. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22546. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22547. return this._processPointerDown(pickResult, evt);
  22548. };
  22549. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22550. var _this = this;
  22551. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22552. this._pickedDownMesh = pickResult.pickedMesh;
  22553. var actionManager = pickResult.pickedMesh.actionManager;
  22554. if (actionManager) {
  22555. if (actionManager.hasPickTriggers) {
  22556. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22557. switch (evt.button) {
  22558. case 0:
  22559. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22560. break;
  22561. case 1:
  22562. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22563. break;
  22564. case 2:
  22565. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22566. break;
  22567. }
  22568. }
  22569. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22570. window.setTimeout(function () {
  22571. 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);
  22572. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22573. if (_this._totalPointersPressed !== 0 &&
  22574. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22575. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22576. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22577. _this._startingPointerTime = 0;
  22578. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22579. }
  22580. }
  22581. }, Scene.LongPressDelay);
  22582. }
  22583. }
  22584. }
  22585. if (pickResult) {
  22586. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22587. if (this.onPointerDown) {
  22588. this.onPointerDown(evt, pickResult, type);
  22589. }
  22590. if (this.onPointerObservable.hasObservers()) {
  22591. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22592. this.onPointerObservable.notifyObservers(pi, type);
  22593. }
  22594. }
  22595. return this;
  22596. };
  22597. /**
  22598. * Use this method to simulate a pointer up on a mesh
  22599. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22600. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22601. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22602. */
  22603. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22604. var evt = new PointerEvent("pointerup", pointerEventInit);
  22605. var clickInfo = new ClickInfo();
  22606. clickInfo.singleClick = true;
  22607. clickInfo.ignore = true;
  22608. return this._processPointerUp(pickResult, evt, clickInfo);
  22609. };
  22610. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22611. if (pickResult && pickResult && pickResult.pickedMesh) {
  22612. this._pickedUpMesh = pickResult.pickedMesh;
  22613. if (this._pickedDownMesh === this._pickedUpMesh) {
  22614. if (this.onPointerPick) {
  22615. this.onPointerPick(evt, pickResult);
  22616. }
  22617. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22618. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  22619. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  22620. this.onPointerObservable.notifyObservers(pi, type_1);
  22621. }
  22622. }
  22623. if (pickResult.pickedMesh.actionManager) {
  22624. if (clickInfo.ignore) {
  22625. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22626. }
  22627. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22628. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22629. }
  22630. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22631. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22632. }
  22633. }
  22634. }
  22635. if (this._pickedDownMesh &&
  22636. this._pickedDownMesh.actionManager &&
  22637. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22638. this._pickedDownMesh !== this._pickedUpMesh) {
  22639. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22640. }
  22641. var type = BABYLON.PointerEventTypes.POINTERUP;
  22642. if (this.onPointerObservable.hasObservers()) {
  22643. if (!clickInfo.ignore) {
  22644. if (!clickInfo.hasSwiped) {
  22645. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22646. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  22647. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  22648. this.onPointerObservable.notifyObservers(pi, type_2);
  22649. }
  22650. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22651. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22652. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  22653. this.onPointerObservable.notifyObservers(pi, type_3);
  22654. }
  22655. }
  22656. }
  22657. else {
  22658. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22659. this.onPointerObservable.notifyObservers(pi, type);
  22660. }
  22661. }
  22662. if (this.onPointerUp) {
  22663. this.onPointerUp(evt, pickResult, type);
  22664. }
  22665. return this;
  22666. };
  22667. /**
  22668. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22669. * @param attachUp defines if you want to attach events to pointerup
  22670. * @param attachDown defines if you want to attach events to pointerdown
  22671. * @param attachMove defines if you want to attach events to pointermove
  22672. */
  22673. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22674. var _this = this;
  22675. if (attachUp === void 0) { attachUp = true; }
  22676. if (attachDown === void 0) { attachDown = true; }
  22677. if (attachMove === void 0) { attachMove = true; }
  22678. this._initActionManager = function (act, clickInfo) {
  22679. if (!_this._meshPickProceed) {
  22680. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22681. _this._currentPickResult = pickResult;
  22682. if (pickResult) {
  22683. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22684. }
  22685. _this._meshPickProceed = true;
  22686. }
  22687. return act;
  22688. };
  22689. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22690. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22691. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22692. btn !== _this._previousButtonPressed) {
  22693. _this._doubleClickOccured = false;
  22694. clickInfo.singleClick = true;
  22695. clickInfo.ignore = false;
  22696. cb(clickInfo, _this._currentPickResult);
  22697. }
  22698. };
  22699. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22700. var clickInfo = new ClickInfo();
  22701. _this._currentPickResult = null;
  22702. var act = null;
  22703. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22704. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22705. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22706. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22707. act = _this._initActionManager(act, clickInfo);
  22708. if (act)
  22709. checkPicking = act.hasPickTriggers;
  22710. }
  22711. if (checkPicking) {
  22712. var btn = evt.button;
  22713. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22714. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22715. if (!clickInfo.hasSwiped) {
  22716. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22717. if (!checkSingleClickImmediately) {
  22718. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22719. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22720. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22721. act = _this._initActionManager(act, clickInfo);
  22722. if (act)
  22723. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22724. }
  22725. }
  22726. if (checkSingleClickImmediately) {
  22727. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22728. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22729. btn !== _this._previousButtonPressed) {
  22730. clickInfo.singleClick = true;
  22731. cb(clickInfo, _this._currentPickResult);
  22732. }
  22733. }
  22734. else {
  22735. // wait that no double click has been raised during the double click delay
  22736. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22737. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22738. }
  22739. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22740. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22741. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22742. act = _this._initActionManager(act, clickInfo);
  22743. if (act)
  22744. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22745. }
  22746. if (checkDoubleClick) {
  22747. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22748. if (btn === _this._previousButtonPressed &&
  22749. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22750. !_this._doubleClickOccured) {
  22751. // pointer has not moved for 2 clicks, it's a double click
  22752. if (!clickInfo.hasSwiped &&
  22753. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22754. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22755. _this._previousStartingPointerTime = 0;
  22756. _this._doubleClickOccured = true;
  22757. clickInfo.doubleClick = true;
  22758. clickInfo.ignore = false;
  22759. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22760. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22761. }
  22762. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22763. cb(clickInfo, _this._currentPickResult);
  22764. }
  22765. else {
  22766. _this._doubleClickOccured = false;
  22767. _this._previousStartingPointerTime = _this._startingPointerTime;
  22768. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22769. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22770. _this._previousButtonPressed = btn;
  22771. if (Scene.ExclusiveDoubleClickMode) {
  22772. if (_this._previousDelayedSimpleClickTimeout) {
  22773. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22774. }
  22775. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22776. cb(clickInfo, _this._previousPickResult);
  22777. }
  22778. else {
  22779. cb(clickInfo, _this._currentPickResult);
  22780. }
  22781. }
  22782. }
  22783. else {
  22784. _this._doubleClickOccured = false;
  22785. _this._previousStartingPointerTime = _this._startingPointerTime;
  22786. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22787. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22788. _this._previousButtonPressed = btn;
  22789. }
  22790. }
  22791. }
  22792. }
  22793. clickInfo.ignore = true;
  22794. cb(clickInfo, _this._currentPickResult);
  22795. };
  22796. this._spritePredicate = function (sprite) {
  22797. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22798. };
  22799. this._onPointerMove = function (evt) {
  22800. _this._updatePointerPosition(evt);
  22801. // PreObservable support
  22802. if (_this.onPrePointerObservable.hasObservers()) {
  22803. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22804. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22805. _this.onPrePointerObservable.notifyObservers(pi, type);
  22806. if (pi.skipOnPointerObservable) {
  22807. return;
  22808. }
  22809. }
  22810. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22811. return;
  22812. }
  22813. if (!_this.pointerMovePredicate) {
  22814. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22815. }
  22816. // Meshes
  22817. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22818. _this._processPointerMove(pickResult, evt);
  22819. };
  22820. this._onPointerDown = function (evt) {
  22821. _this._totalPointersPressed++;
  22822. _this._pickedDownMesh = null;
  22823. _this._meshPickProceed = false;
  22824. _this._updatePointerPosition(evt);
  22825. if (_this.preventDefaultOnPointerDown && canvas) {
  22826. evt.preventDefault();
  22827. canvas.focus();
  22828. }
  22829. // PreObservable support
  22830. if (_this.onPrePointerObservable.hasObservers()) {
  22831. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22832. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22833. _this.onPrePointerObservable.notifyObservers(pi, type);
  22834. if (pi.skipOnPointerObservable) {
  22835. return;
  22836. }
  22837. }
  22838. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22839. return;
  22840. }
  22841. _this._startingPointerPosition.x = _this._pointerX;
  22842. _this._startingPointerPosition.y = _this._pointerY;
  22843. _this._startingPointerTime = new Date().getTime();
  22844. if (!_this.pointerDownPredicate) {
  22845. _this.pointerDownPredicate = function (mesh) {
  22846. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22847. };
  22848. }
  22849. // Meshes
  22850. _this._pickedDownMesh = null;
  22851. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22852. _this._processPointerDown(pickResult, evt);
  22853. // Sprites
  22854. _this._pickedDownSprite = null;
  22855. if (_this.spriteManagers.length > 0) {
  22856. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22857. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22858. if (pickResult.pickedSprite.actionManager) {
  22859. _this._pickedDownSprite = pickResult.pickedSprite;
  22860. switch (evt.button) {
  22861. case 0:
  22862. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22863. break;
  22864. case 1:
  22865. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22866. break;
  22867. case 2:
  22868. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22869. break;
  22870. }
  22871. if (pickResult.pickedSprite.actionManager) {
  22872. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22873. }
  22874. }
  22875. }
  22876. }
  22877. };
  22878. this._onPointerUp = function (evt) {
  22879. if (_this._totalPointersPressed === 0) {
  22880. return; // So we need to test it the pointer down was pressed before.
  22881. }
  22882. _this._totalPointersPressed--;
  22883. _this._pickedUpMesh = null;
  22884. _this._meshPickProceed = false;
  22885. _this._updatePointerPosition(evt);
  22886. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22887. // PreObservable support
  22888. if (_this.onPrePointerObservable.hasObservers()) {
  22889. if (!clickInfo.ignore) {
  22890. if (!clickInfo.hasSwiped) {
  22891. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22892. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22893. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22894. _this.onPrePointerObservable.notifyObservers(pi, type);
  22895. if (pi.skipOnPointerObservable) {
  22896. return;
  22897. }
  22898. }
  22899. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22900. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22901. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22902. _this.onPrePointerObservable.notifyObservers(pi, type);
  22903. if (pi.skipOnPointerObservable) {
  22904. return;
  22905. }
  22906. }
  22907. }
  22908. }
  22909. else {
  22910. var type = BABYLON.PointerEventTypes.POINTERUP;
  22911. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22912. _this.onPrePointerObservable.notifyObservers(pi, type);
  22913. if (pi.skipOnPointerObservable) {
  22914. return;
  22915. }
  22916. }
  22917. }
  22918. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22919. return;
  22920. }
  22921. if (!_this.pointerUpPredicate) {
  22922. _this.pointerUpPredicate = function (mesh) {
  22923. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22924. };
  22925. }
  22926. // Meshes
  22927. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22928. _this._initActionManager(null, clickInfo);
  22929. }
  22930. if (!pickResult) {
  22931. pickResult = _this._currentPickResult;
  22932. }
  22933. _this._processPointerUp(pickResult, evt, clickInfo);
  22934. // Sprites
  22935. if (_this.spriteManagers.length > 0) {
  22936. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22937. if (spritePickResult) {
  22938. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22939. if (spritePickResult.pickedSprite.actionManager) {
  22940. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22941. if (spritePickResult.pickedSprite.actionManager) {
  22942. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22943. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22944. }
  22945. }
  22946. }
  22947. }
  22948. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22949. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22950. }
  22951. }
  22952. }
  22953. _this._previousPickResult = _this._currentPickResult;
  22954. });
  22955. };
  22956. this._onKeyDown = function (evt) {
  22957. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22958. if (_this.onPreKeyboardObservable.hasObservers()) {
  22959. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22960. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22961. if (pi.skipOnPointerObservable) {
  22962. return;
  22963. }
  22964. }
  22965. if (_this.onKeyboardObservable.hasObservers()) {
  22966. var pi = new BABYLON.KeyboardInfo(type, evt);
  22967. _this.onKeyboardObservable.notifyObservers(pi, type);
  22968. }
  22969. if (_this.actionManager) {
  22970. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22971. }
  22972. };
  22973. this._onKeyUp = function (evt) {
  22974. var type = BABYLON.KeyboardEventTypes.KEYUP;
  22975. if (_this.onPreKeyboardObservable.hasObservers()) {
  22976. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22977. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22978. if (pi.skipOnPointerObservable) {
  22979. return;
  22980. }
  22981. }
  22982. if (_this.onKeyboardObservable.hasObservers()) {
  22983. var pi = new BABYLON.KeyboardInfo(type, evt);
  22984. _this.onKeyboardObservable.notifyObservers(pi, type);
  22985. }
  22986. if (_this.actionManager) {
  22987. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22988. }
  22989. };
  22990. var engine = this.getEngine();
  22991. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  22992. if (!canvas) {
  22993. return;
  22994. }
  22995. canvas.addEventListener("keydown", _this._onKeyDown, false);
  22996. canvas.addEventListener("keyup", _this._onKeyUp, false);
  22997. });
  22998. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  22999. if (!canvas) {
  23000. return;
  23001. }
  23002. canvas.removeEventListener("keydown", _this._onKeyDown);
  23003. canvas.removeEventListener("keyup", _this._onKeyUp);
  23004. });
  23005. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23006. var canvas = this._engine.getRenderingCanvas();
  23007. if (!canvas) {
  23008. return;
  23009. }
  23010. if (attachMove) {
  23011. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  23012. // Wheel
  23013. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  23014. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  23015. }
  23016. if (attachDown) {
  23017. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  23018. }
  23019. if (attachUp) {
  23020. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  23021. }
  23022. canvas.tabIndex = 1;
  23023. };
  23024. Scene.prototype.detachControl = function () {
  23025. var engine = this.getEngine();
  23026. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23027. var canvas = engine.getRenderingCanvas();
  23028. if (!canvas) {
  23029. return;
  23030. }
  23031. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  23032. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  23033. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  23034. if (this._onCanvasBlurObserver) {
  23035. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  23036. }
  23037. if (this._onCanvasFocusObserver) {
  23038. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  23039. }
  23040. // Wheel
  23041. canvas.removeEventListener('mousewheel', this._onPointerMove);
  23042. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  23043. // Keyboard
  23044. canvas.removeEventListener("keydown", this._onKeyDown);
  23045. canvas.removeEventListener("keyup", this._onKeyUp);
  23046. // Observables
  23047. this.onKeyboardObservable.clear();
  23048. this.onPreKeyboardObservable.clear();
  23049. this.onPointerObservable.clear();
  23050. this.onPrePointerObservable.clear();
  23051. };
  23052. /**
  23053. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  23054. * Delay loaded resources are not taking in account
  23055. * @return true if all required resources are ready
  23056. */
  23057. Scene.prototype.isReady = function () {
  23058. if (this._isDisposed) {
  23059. return false;
  23060. }
  23061. if (this._pendingData.length > 0) {
  23062. return false;
  23063. }
  23064. var index;
  23065. var engine = this.getEngine();
  23066. // Geometries
  23067. for (index = 0; index < this._geometries.length; index++) {
  23068. var geometry = this._geometries[index];
  23069. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23070. return false;
  23071. }
  23072. }
  23073. // Meshes
  23074. for (index = 0; index < this.meshes.length; index++) {
  23075. var mesh = this.meshes[index];
  23076. if (!mesh.isEnabled()) {
  23077. continue;
  23078. }
  23079. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  23080. continue;
  23081. }
  23082. if (!mesh.isReady(true)) {
  23083. return false;
  23084. }
  23085. // Effect layers
  23086. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  23087. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  23088. var layer = _a[_i];
  23089. if (!layer.hasMesh(mesh)) {
  23090. continue;
  23091. }
  23092. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  23093. var subMesh = _c[_b];
  23094. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  23095. return false;
  23096. }
  23097. }
  23098. }
  23099. }
  23100. // Particles
  23101. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  23102. var particleSystem = _e[_d];
  23103. if (!particleSystem.isReady()) {
  23104. return false;
  23105. }
  23106. }
  23107. return true;
  23108. };
  23109. Scene.prototype.resetCachedMaterial = function () {
  23110. this._cachedMaterial = null;
  23111. this._cachedEffect = null;
  23112. this._cachedVisibility = null;
  23113. };
  23114. Scene.prototype.registerBeforeRender = function (func) {
  23115. this.onBeforeRenderObservable.add(func);
  23116. };
  23117. Scene.prototype.unregisterBeforeRender = function (func) {
  23118. this.onBeforeRenderObservable.removeCallback(func);
  23119. };
  23120. Scene.prototype.registerAfterRender = function (func) {
  23121. this.onAfterRenderObservable.add(func);
  23122. };
  23123. Scene.prototype.unregisterAfterRender = function (func) {
  23124. this.onAfterRenderObservable.removeCallback(func);
  23125. };
  23126. Scene.prototype._executeOnceBeforeRender = function (func) {
  23127. var _this = this;
  23128. var execFunc = function () {
  23129. func();
  23130. setTimeout(function () {
  23131. _this.unregisterBeforeRender(execFunc);
  23132. });
  23133. };
  23134. this.registerBeforeRender(execFunc);
  23135. };
  23136. /**
  23137. * The provided function will run before render once and will be disposed afterwards.
  23138. * A timeout delay can be provided so that the function will be executed in N ms.
  23139. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  23140. * @param func The function to be executed.
  23141. * @param timeout optional delay in ms
  23142. */
  23143. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  23144. var _this = this;
  23145. if (timeout !== undefined) {
  23146. setTimeout(function () {
  23147. _this._executeOnceBeforeRender(func);
  23148. }, timeout);
  23149. }
  23150. else {
  23151. this._executeOnceBeforeRender(func);
  23152. }
  23153. };
  23154. Scene.prototype._addPendingData = function (data) {
  23155. this._pendingData.push(data);
  23156. };
  23157. Scene.prototype._removePendingData = function (data) {
  23158. var wasLoading = this.isLoading;
  23159. var index = this._pendingData.indexOf(data);
  23160. if (index !== -1) {
  23161. this._pendingData.splice(index, 1);
  23162. }
  23163. if (wasLoading && !this.isLoading) {
  23164. this.onDataLoadedObservable.notifyObservers(this);
  23165. }
  23166. };
  23167. Scene.prototype.getWaitingItemsCount = function () {
  23168. return this._pendingData.length;
  23169. };
  23170. Object.defineProperty(Scene.prototype, "isLoading", {
  23171. get: function () {
  23172. return this._pendingData.length > 0;
  23173. },
  23174. enumerable: true,
  23175. configurable: true
  23176. });
  23177. /**
  23178. * Registers a function to be executed when the scene is ready.
  23179. * @param {Function} func - the function to be executed.
  23180. */
  23181. Scene.prototype.executeWhenReady = function (func) {
  23182. var _this = this;
  23183. this.onReadyObservable.add(func);
  23184. if (this._executeWhenReadyTimeoutId !== -1) {
  23185. return;
  23186. }
  23187. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23188. _this._checkIsReady();
  23189. }, 150);
  23190. };
  23191. /**
  23192. * Returns a promise that resolves when the scene is ready.
  23193. * @returns A promise that resolves when the scene is ready.
  23194. */
  23195. Scene.prototype.whenReadyAsync = function () {
  23196. var _this = this;
  23197. return new Promise(function (resolve) {
  23198. _this.executeWhenReady(function () {
  23199. resolve();
  23200. });
  23201. });
  23202. };
  23203. Scene.prototype._checkIsReady = function () {
  23204. var _this = this;
  23205. if (this.isReady()) {
  23206. this.onReadyObservable.notifyObservers(this);
  23207. this.onReadyObservable.clear();
  23208. this._executeWhenReadyTimeoutId = -1;
  23209. return;
  23210. }
  23211. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23212. _this._checkIsReady();
  23213. }, 150);
  23214. };
  23215. // Animations
  23216. /**
  23217. * Will start the animation sequence of a given target
  23218. * @param target defines the target
  23219. * @param from defines from which frame should animation start
  23220. * @param to defines until which frame should animation run.
  23221. * @param weight defines the weight to apply to the animation (1.0 by default)
  23222. * @param loop defines if the animation loops
  23223. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23224. * @param onAnimationEnd defines the function to be executed when the animation ends
  23225. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23226. * @returns the animatable object created for this animation
  23227. * @see BABYLON.Animatable
  23228. */
  23229. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  23230. if (weight === void 0) { weight = 1.0; }
  23231. if (speedRatio === void 0) { speedRatio = 1.0; }
  23232. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  23233. returnedAnimatable.weight = weight;
  23234. return returnedAnimatable;
  23235. };
  23236. /**
  23237. * Will start the animation sequence of a given target
  23238. * @param target defines the target
  23239. * @param from defines from which frame should animation start
  23240. * @param to defines until which frame should animation run.
  23241. * @param loop defines if the animation loops
  23242. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23243. * @param onAnimationEnd defines the function to be executed when the animation ends
  23244. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23245. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  23246. * @returns the animatable object created for this animation
  23247. * @see BABYLON.Animatable
  23248. */
  23249. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  23250. if (speedRatio === void 0) { speedRatio = 1.0; }
  23251. if (stopCurrent === void 0) { stopCurrent = true; }
  23252. if (from > to && speedRatio > 0) {
  23253. speedRatio *= -1;
  23254. }
  23255. if (stopCurrent) {
  23256. this.stopAnimation(target);
  23257. }
  23258. if (!animatable) {
  23259. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  23260. }
  23261. // Local animations
  23262. if (target.animations) {
  23263. animatable.appendAnimations(target, target.animations);
  23264. }
  23265. // Children animations
  23266. if (target.getAnimatables) {
  23267. var animatables = target.getAnimatables();
  23268. for (var index = 0; index < animatables.length; index++) {
  23269. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  23270. }
  23271. }
  23272. if (stopCurrent) {
  23273. animatable.reset();
  23274. }
  23275. return animatable;
  23276. };
  23277. /**
  23278. * Begin a new animation on a given node
  23279. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23280. * @param {BABYLON.Animation[]} defines the list of animations to start
  23281. * @param {number} from defines the initial value
  23282. * @param {number} to defines the final value
  23283. * @param {boolean} loop defines if you want animation to loop (off by default)
  23284. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23285. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23286. * @returns the list of created animatables
  23287. */
  23288. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23289. if (speedRatio === undefined) {
  23290. speedRatio = 1.0;
  23291. }
  23292. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  23293. return animatable;
  23294. };
  23295. /**
  23296. * Begin a new animation on a given node and its hierarchy
  23297. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23298. * @param {boolean} 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.
  23299. * @param {BABYLON.Animation[]} defines the list of animations to start
  23300. * @param {number} from defines the initial value
  23301. * @param {number} to defines the final value
  23302. * @param {boolean} loop defines if you want animation to loop (off by default)
  23303. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23304. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23305. * @returns the list of animatables created for all nodes
  23306. */
  23307. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23308. var children = target.getDescendants(directDescendantsOnly);
  23309. var result = [];
  23310. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  23311. var child = children_1[_i];
  23312. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  23313. }
  23314. return result;
  23315. };
  23316. Scene.prototype.getAnimatableByTarget = function (target) {
  23317. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23318. if (this._activeAnimatables[index].target === target) {
  23319. return this._activeAnimatables[index];
  23320. }
  23321. }
  23322. return null;
  23323. };
  23324. Object.defineProperty(Scene.prototype, "animatables", {
  23325. get: function () {
  23326. return this._activeAnimatables;
  23327. },
  23328. enumerable: true,
  23329. configurable: true
  23330. });
  23331. /**
  23332. * Will stop the animation of the given target
  23333. * @param target - the target
  23334. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  23335. * @see beginAnimation
  23336. */
  23337. Scene.prototype.stopAnimation = function (target, animationName) {
  23338. var animatable = this.getAnimatableByTarget(target);
  23339. if (animatable) {
  23340. animatable.stop(animationName);
  23341. }
  23342. };
  23343. /**
  23344. * Stops and removes all animations that have been applied to the scene
  23345. */
  23346. Scene.prototype.stopAllAnimations = function () {
  23347. if (this._activeAnimatables) {
  23348. for (var i = 0; i < this._activeAnimatables.length; i++) {
  23349. this._activeAnimatables[i].stop();
  23350. }
  23351. this._activeAnimatables = [];
  23352. }
  23353. };
  23354. Scene.prototype._animate = function () {
  23355. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  23356. return;
  23357. }
  23358. // Getting time
  23359. var now = BABYLON.Tools.Now;
  23360. if (!this._animationTimeLast) {
  23361. if (this._pendingData.length > 0) {
  23362. return;
  23363. }
  23364. this._animationTimeLast = now;
  23365. }
  23366. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  23367. this._animationTime += deltaTime;
  23368. this._animationTimeLast = now;
  23369. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23370. this._activeAnimatables[index]._animate(this._animationTime);
  23371. }
  23372. // Late animation bindings
  23373. this._processLateAnimationBindings();
  23374. };
  23375. /** @ignore */
  23376. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  23377. var target = runtimeAnimation.target;
  23378. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  23379. if (!target._lateAnimationHolders) {
  23380. target._lateAnimationHolders = {};
  23381. }
  23382. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  23383. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  23384. totalWeight: 0,
  23385. animations: []
  23386. };
  23387. }
  23388. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  23389. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  23390. };
  23391. Scene.prototype._processLateAnimationBindings = function () {
  23392. if (!this._registeredForLateAnimationBindings.length) {
  23393. return;
  23394. }
  23395. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  23396. var target = this._registeredForLateAnimationBindings.data[index];
  23397. for (var path in target._lateAnimationHolders) {
  23398. var holder = target._lateAnimationHolders[path];
  23399. // Sanity check
  23400. if (!holder.animations[0].originalValue.scaleAndAddToRef) {
  23401. continue;
  23402. }
  23403. var normalizer = 1.0;
  23404. var finalValue = void 0;
  23405. if (holder.totalWeight < 1.0) {
  23406. // We need to mix the original value in
  23407. var originalValue = holder.animations[0].originalValue;
  23408. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  23409. }
  23410. else {
  23411. // We need to normalize the weights
  23412. normalizer = holder.totalWeight;
  23413. }
  23414. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  23415. var runtimeAnimation = holder.animations[animIndex];
  23416. if (finalValue) {
  23417. runtimeAnimation.currentValue.scaleAndAddToRef(runtimeAnimation.weight / normalizer, finalValue);
  23418. }
  23419. else {
  23420. finalValue = runtimeAnimation.currentValue.scale(runtimeAnimation.weight / normalizer);
  23421. }
  23422. }
  23423. runtimeAnimation.target[path] = finalValue;
  23424. }
  23425. target._lateAnimationHolders = {};
  23426. }
  23427. this._registeredForLateAnimationBindings.reset();
  23428. };
  23429. // Matrix
  23430. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  23431. this._useAlternateCameraConfiguration = active;
  23432. };
  23433. Scene.prototype.getViewMatrix = function () {
  23434. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  23435. };
  23436. Scene.prototype.getProjectionMatrix = function () {
  23437. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23438. };
  23439. Scene.prototype.getTransformMatrix = function () {
  23440. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23441. };
  23442. Scene.prototype.setTransformMatrix = function (view, projection) {
  23443. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23444. return;
  23445. }
  23446. this._viewUpdateFlag = view.updateFlag;
  23447. this._projectionUpdateFlag = projection.updateFlag;
  23448. this._viewMatrix = view;
  23449. this._projectionMatrix = projection;
  23450. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23451. // Update frustum
  23452. if (!this._frustumPlanes) {
  23453. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23454. }
  23455. else {
  23456. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23457. }
  23458. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23459. var otherCamera = this.activeCamera._alternateCamera;
  23460. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23461. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23462. }
  23463. if (this._sceneUbo.useUbo) {
  23464. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23465. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23466. this._sceneUbo.update();
  23467. }
  23468. };
  23469. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23470. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23471. return;
  23472. }
  23473. this._alternateViewUpdateFlag = view.updateFlag;
  23474. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23475. this._alternateViewMatrix = view;
  23476. this._alternateProjectionMatrix = projection;
  23477. if (!this._alternateTransformMatrix) {
  23478. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23479. }
  23480. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23481. if (!this._alternateSceneUbo) {
  23482. this._createAlternateUbo();
  23483. }
  23484. if (this._alternateSceneUbo.useUbo) {
  23485. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23486. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23487. this._alternateSceneUbo.update();
  23488. }
  23489. };
  23490. Scene.prototype.getSceneUniformBuffer = function () {
  23491. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23492. };
  23493. // Methods
  23494. Scene.prototype.getUniqueId = function () {
  23495. var result = Scene._uniqueIdCounter;
  23496. Scene._uniqueIdCounter++;
  23497. return result;
  23498. };
  23499. Scene.prototype.addMesh = function (newMesh) {
  23500. this.meshes.push(newMesh);
  23501. //notify the collision coordinator
  23502. if (this.collisionCoordinator) {
  23503. this.collisionCoordinator.onMeshAdded(newMesh);
  23504. }
  23505. newMesh._resyncLightSources();
  23506. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23507. };
  23508. Scene.prototype.removeMesh = function (toRemove) {
  23509. var index = this.meshes.indexOf(toRemove);
  23510. if (index !== -1) {
  23511. // Remove from the scene if mesh found
  23512. this.meshes.splice(index, 1);
  23513. }
  23514. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23515. return index;
  23516. };
  23517. Scene.prototype.addTransformNode = function (newTransformNode) {
  23518. this.transformNodes.push(newTransformNode);
  23519. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23520. };
  23521. Scene.prototype.removeTransformNode = function (toRemove) {
  23522. var index = this.transformNodes.indexOf(toRemove);
  23523. if (index !== -1) {
  23524. // Remove from the scene if found
  23525. this.transformNodes.splice(index, 1);
  23526. }
  23527. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23528. return index;
  23529. };
  23530. Scene.prototype.removeSkeleton = function (toRemove) {
  23531. var index = this.skeletons.indexOf(toRemove);
  23532. if (index !== -1) {
  23533. // Remove from the scene if found
  23534. this.skeletons.splice(index, 1);
  23535. }
  23536. return index;
  23537. };
  23538. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23539. var index = this.morphTargetManagers.indexOf(toRemove);
  23540. if (index !== -1) {
  23541. // Remove from the scene if found
  23542. this.morphTargetManagers.splice(index, 1);
  23543. }
  23544. return index;
  23545. };
  23546. Scene.prototype.removeLight = function (toRemove) {
  23547. var index = this.lights.indexOf(toRemove);
  23548. if (index !== -1) {
  23549. // Remove from meshes
  23550. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23551. var mesh = _a[_i];
  23552. mesh._removeLightSource(toRemove);
  23553. }
  23554. // Remove from the scene if mesh found
  23555. this.lights.splice(index, 1);
  23556. this.sortLightsByPriority();
  23557. }
  23558. this.onLightRemovedObservable.notifyObservers(toRemove);
  23559. return index;
  23560. };
  23561. Scene.prototype.removeCamera = function (toRemove) {
  23562. var index = this.cameras.indexOf(toRemove);
  23563. if (index !== -1) {
  23564. // Remove from the scene if mesh found
  23565. this.cameras.splice(index, 1);
  23566. }
  23567. // Remove from activeCameras
  23568. var index2 = this.activeCameras.indexOf(toRemove);
  23569. if (index2 !== -1) {
  23570. // Remove from the scene if mesh found
  23571. this.activeCameras.splice(index2, 1);
  23572. }
  23573. // Reset the activeCamera
  23574. if (this.activeCamera === toRemove) {
  23575. if (this.cameras.length > 0) {
  23576. this.activeCamera = this.cameras[0];
  23577. }
  23578. else {
  23579. this.activeCamera = null;
  23580. }
  23581. }
  23582. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23583. return index;
  23584. };
  23585. Scene.prototype.removeParticleSystem = function (toRemove) {
  23586. var index = this.particleSystems.indexOf(toRemove);
  23587. if (index !== -1) {
  23588. this.particleSystems.splice(index, 1);
  23589. }
  23590. return index;
  23591. };
  23592. ;
  23593. Scene.prototype.removeAnimation = function (toRemove) {
  23594. var index = this.animations.indexOf(toRemove);
  23595. if (index !== -1) {
  23596. this.animations.splice(index, 1);
  23597. }
  23598. return index;
  23599. };
  23600. ;
  23601. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23602. var index = this.multiMaterials.indexOf(toRemove);
  23603. if (index !== -1) {
  23604. this.multiMaterials.splice(index, 1);
  23605. }
  23606. return index;
  23607. };
  23608. ;
  23609. Scene.prototype.removeMaterial = function (toRemove) {
  23610. var index = this.materials.indexOf(toRemove);
  23611. if (index !== -1) {
  23612. this.materials.splice(index, 1);
  23613. }
  23614. return index;
  23615. };
  23616. ;
  23617. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23618. var index = this.lensFlareSystems.indexOf(toRemove);
  23619. if (index !== -1) {
  23620. this.lensFlareSystems.splice(index, 1);
  23621. }
  23622. return index;
  23623. };
  23624. ;
  23625. Scene.prototype.removeActionManager = function (toRemove) {
  23626. var index = this._actionManagers.indexOf(toRemove);
  23627. if (index !== -1) {
  23628. this._actionManagers.splice(index, 1);
  23629. }
  23630. return index;
  23631. };
  23632. ;
  23633. Scene.prototype.addLight = function (newLight) {
  23634. this.lights.push(newLight);
  23635. this.sortLightsByPriority();
  23636. // Add light to all meshes (To support if the light is removed and then readded)
  23637. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23638. var mesh = _a[_i];
  23639. if (mesh._lightSources.indexOf(newLight) === -1) {
  23640. mesh._lightSources.push(newLight);
  23641. mesh._resyncLightSources();
  23642. }
  23643. }
  23644. this.onNewLightAddedObservable.notifyObservers(newLight);
  23645. };
  23646. Scene.prototype.sortLightsByPriority = function () {
  23647. if (this.requireLightSorting) {
  23648. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23649. }
  23650. };
  23651. Scene.prototype.addCamera = function (newCamera) {
  23652. this.cameras.push(newCamera);
  23653. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23654. };
  23655. Scene.prototype.addSkeleton = function (newSkeleton) {
  23656. this.skeletons.push(newSkeleton);
  23657. };
  23658. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23659. this.particleSystems.push(newParticleSystem);
  23660. };
  23661. Scene.prototype.addAnimation = function (newAnimation) {
  23662. this.animations.push(newAnimation);
  23663. };
  23664. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23665. this.multiMaterials.push(newMultiMaterial);
  23666. };
  23667. Scene.prototype.addMaterial = function (newMaterial) {
  23668. this.materials.push(newMaterial);
  23669. };
  23670. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23671. this.morphTargetManagers.push(newMorphTargetManager);
  23672. };
  23673. Scene.prototype.addGeometry = function (newGeometrie) {
  23674. this._geometries.push(newGeometrie);
  23675. };
  23676. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23677. this.lensFlareSystems.push(newLensFlareSystem);
  23678. };
  23679. Scene.prototype.addActionManager = function (newActionManager) {
  23680. this._actionManagers.push(newActionManager);
  23681. };
  23682. /**
  23683. * Switch active camera
  23684. * @param {Camera} newCamera - new active camera
  23685. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23686. */
  23687. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23688. if (attachControl === void 0) { attachControl = true; }
  23689. var canvas = this._engine.getRenderingCanvas();
  23690. if (!canvas) {
  23691. return;
  23692. }
  23693. if (this.activeCamera) {
  23694. this.activeCamera.detachControl(canvas);
  23695. }
  23696. this.activeCamera = newCamera;
  23697. if (attachControl) {
  23698. newCamera.attachControl(canvas);
  23699. }
  23700. };
  23701. /**
  23702. * sets the active camera of the scene using its ID
  23703. * @param {string} id - the camera's ID
  23704. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23705. * @see activeCamera
  23706. */
  23707. Scene.prototype.setActiveCameraByID = function (id) {
  23708. var camera = this.getCameraByID(id);
  23709. if (camera) {
  23710. this.activeCamera = camera;
  23711. return camera;
  23712. }
  23713. return null;
  23714. };
  23715. /**
  23716. * sets the active camera of the scene using its name
  23717. * @param {string} name - the camera's name
  23718. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23719. * @see activeCamera
  23720. */
  23721. Scene.prototype.setActiveCameraByName = function (name) {
  23722. var camera = this.getCameraByName(name);
  23723. if (camera) {
  23724. this.activeCamera = camera;
  23725. return camera;
  23726. }
  23727. return null;
  23728. };
  23729. /**
  23730. * get an animation group using its name
  23731. * @param {string} the material's name
  23732. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23733. */
  23734. Scene.prototype.getAnimationGroupByName = function (name) {
  23735. for (var index = 0; index < this.animationGroups.length; index++) {
  23736. if (this.animationGroups[index].name === name) {
  23737. return this.animationGroups[index];
  23738. }
  23739. }
  23740. return null;
  23741. };
  23742. /**
  23743. * get a material using its id
  23744. * @param {string} the material's ID
  23745. * @return {BABYLON.Material|null} the material or null if none found.
  23746. */
  23747. Scene.prototype.getMaterialByID = function (id) {
  23748. for (var index = 0; index < this.materials.length; index++) {
  23749. if (this.materials[index].id === id) {
  23750. return this.materials[index];
  23751. }
  23752. }
  23753. return null;
  23754. };
  23755. /**
  23756. * get a material using its name
  23757. * @param {string} the material's name
  23758. * @return {BABYLON.Material|null} the material or null if none found.
  23759. */
  23760. Scene.prototype.getMaterialByName = function (name) {
  23761. for (var index = 0; index < this.materials.length; index++) {
  23762. if (this.materials[index].name === name) {
  23763. return this.materials[index];
  23764. }
  23765. }
  23766. return null;
  23767. };
  23768. Scene.prototype.getLensFlareSystemByName = function (name) {
  23769. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23770. if (this.lensFlareSystems[index].name === name) {
  23771. return this.lensFlareSystems[index];
  23772. }
  23773. }
  23774. return null;
  23775. };
  23776. Scene.prototype.getLensFlareSystemByID = function (id) {
  23777. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23778. if (this.lensFlareSystems[index].id === id) {
  23779. return this.lensFlareSystems[index];
  23780. }
  23781. }
  23782. return null;
  23783. };
  23784. Scene.prototype.getCameraByID = function (id) {
  23785. for (var index = 0; index < this.cameras.length; index++) {
  23786. if (this.cameras[index].id === id) {
  23787. return this.cameras[index];
  23788. }
  23789. }
  23790. return null;
  23791. };
  23792. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23793. for (var index = 0; index < this.cameras.length; index++) {
  23794. if (this.cameras[index].uniqueId === uniqueId) {
  23795. return this.cameras[index];
  23796. }
  23797. }
  23798. return null;
  23799. };
  23800. /**
  23801. * get a camera using its name
  23802. * @param {string} the camera's name
  23803. * @return {BABYLON.Camera|null} the camera or null if none found.
  23804. */
  23805. Scene.prototype.getCameraByName = function (name) {
  23806. for (var index = 0; index < this.cameras.length; index++) {
  23807. if (this.cameras[index].name === name) {
  23808. return this.cameras[index];
  23809. }
  23810. }
  23811. return null;
  23812. };
  23813. /**
  23814. * get a bone using its id
  23815. * @param {string} the bone's id
  23816. * @return {BABYLON.Bone|null} the bone or null if not found
  23817. */
  23818. Scene.prototype.getBoneByID = function (id) {
  23819. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23820. var skeleton = this.skeletons[skeletonIndex];
  23821. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23822. if (skeleton.bones[boneIndex].id === id) {
  23823. return skeleton.bones[boneIndex];
  23824. }
  23825. }
  23826. }
  23827. return null;
  23828. };
  23829. /**
  23830. * get a bone using its id
  23831. * @param {string} the bone's name
  23832. * @return {BABYLON.Bone|null} the bone or null if not found
  23833. */
  23834. Scene.prototype.getBoneByName = function (name) {
  23835. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23836. var skeleton = this.skeletons[skeletonIndex];
  23837. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23838. if (skeleton.bones[boneIndex].name === name) {
  23839. return skeleton.bones[boneIndex];
  23840. }
  23841. }
  23842. }
  23843. return null;
  23844. };
  23845. /**
  23846. * get a light node using its name
  23847. * @param {string} the light's name
  23848. * @return {BABYLON.Light|null} the light or null if none found.
  23849. */
  23850. Scene.prototype.getLightByName = function (name) {
  23851. for (var index = 0; index < this.lights.length; index++) {
  23852. if (this.lights[index].name === name) {
  23853. return this.lights[index];
  23854. }
  23855. }
  23856. return null;
  23857. };
  23858. /**
  23859. * get a light node using its ID
  23860. * @param {string} the light's id
  23861. * @return {BABYLON.Light|null} the light or null if none found.
  23862. */
  23863. Scene.prototype.getLightByID = function (id) {
  23864. for (var index = 0; index < this.lights.length; index++) {
  23865. if (this.lights[index].id === id) {
  23866. return this.lights[index];
  23867. }
  23868. }
  23869. return null;
  23870. };
  23871. /**
  23872. * get a light node using its scene-generated unique ID
  23873. * @param {number} the light's unique id
  23874. * @return {BABYLON.Light|null} the light or null if none found.
  23875. */
  23876. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23877. for (var index = 0; index < this.lights.length; index++) {
  23878. if (this.lights[index].uniqueId === uniqueId) {
  23879. return this.lights[index];
  23880. }
  23881. }
  23882. return null;
  23883. };
  23884. /**
  23885. * get a particle system by id
  23886. * @param id {number} the particle system id
  23887. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23888. */
  23889. Scene.prototype.getParticleSystemByID = function (id) {
  23890. for (var index = 0; index < this.particleSystems.length; index++) {
  23891. if (this.particleSystems[index].id === id) {
  23892. return this.particleSystems[index];
  23893. }
  23894. }
  23895. return null;
  23896. };
  23897. /**
  23898. * get a geometry using its ID
  23899. * @param {string} the geometry's id
  23900. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23901. */
  23902. Scene.prototype.getGeometryByID = function (id) {
  23903. for (var index = 0; index < this._geometries.length; index++) {
  23904. if (this._geometries[index].id === id) {
  23905. return this._geometries[index];
  23906. }
  23907. }
  23908. return null;
  23909. };
  23910. /**
  23911. * add a new geometry to this scene.
  23912. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23913. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23914. * @return {boolean} was the geometry added or not
  23915. */
  23916. Scene.prototype.pushGeometry = function (geometry, force) {
  23917. if (!force && this.getGeometryByID(geometry.id)) {
  23918. return false;
  23919. }
  23920. this._geometries.push(geometry);
  23921. //notify the collision coordinator
  23922. if (this.collisionCoordinator) {
  23923. this.collisionCoordinator.onGeometryAdded(geometry);
  23924. }
  23925. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  23926. return true;
  23927. };
  23928. /**
  23929. * Removes an existing geometry
  23930. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  23931. * @return {boolean} was the geometry removed or not
  23932. */
  23933. Scene.prototype.removeGeometry = function (geometry) {
  23934. var index = this._geometries.indexOf(geometry);
  23935. if (index > -1) {
  23936. this._geometries.splice(index, 1);
  23937. //notify the collision coordinator
  23938. if (this.collisionCoordinator) {
  23939. this.collisionCoordinator.onGeometryDeleted(geometry);
  23940. }
  23941. this.onGeometryRemovedObservable.notifyObservers(geometry);
  23942. return true;
  23943. }
  23944. return false;
  23945. };
  23946. Scene.prototype.getGeometries = function () {
  23947. return this._geometries;
  23948. };
  23949. /**
  23950. * Get the first added mesh found of a given ID
  23951. * @param {string} id - the id to search for
  23952. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23953. */
  23954. Scene.prototype.getMeshByID = function (id) {
  23955. for (var index = 0; index < this.meshes.length; index++) {
  23956. if (this.meshes[index].id === id) {
  23957. return this.meshes[index];
  23958. }
  23959. }
  23960. return null;
  23961. };
  23962. Scene.prototype.getMeshesByID = function (id) {
  23963. return this.meshes.filter(function (m) {
  23964. return m.id === id;
  23965. });
  23966. };
  23967. /**
  23968. * Get the first added transform node found of a given ID
  23969. * @param {string} id - the id to search for
  23970. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  23971. */
  23972. Scene.prototype.getTransformNodeByID = function (id) {
  23973. for (var index = 0; index < this.transformNodes.length; index++) {
  23974. if (this.transformNodes[index].id === id) {
  23975. return this.transformNodes[index];
  23976. }
  23977. }
  23978. return null;
  23979. };
  23980. Scene.prototype.getTransformNodesByID = function (id) {
  23981. return this.transformNodes.filter(function (m) {
  23982. return m.id === id;
  23983. });
  23984. };
  23985. /**
  23986. * Get a mesh with its auto-generated unique id
  23987. * @param {number} uniqueId - the unique id to search for
  23988. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23989. */
  23990. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  23991. for (var index = 0; index < this.meshes.length; index++) {
  23992. if (this.meshes[index].uniqueId === uniqueId) {
  23993. return this.meshes[index];
  23994. }
  23995. }
  23996. return null;
  23997. };
  23998. /**
  23999. * Get a the last added mesh found of a given ID
  24000. * @param {string} id - the id to search for
  24001. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24002. */
  24003. Scene.prototype.getLastMeshByID = function (id) {
  24004. for (var index = this.meshes.length - 1; index >= 0; index--) {
  24005. if (this.meshes[index].id === id) {
  24006. return this.meshes[index];
  24007. }
  24008. }
  24009. return null;
  24010. };
  24011. /**
  24012. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  24013. * @param {string} id - the id to search for
  24014. * @return {BABYLON.Node|null} the node found or null if not found at all.
  24015. */
  24016. Scene.prototype.getLastEntryByID = function (id) {
  24017. var index;
  24018. for (index = this.meshes.length - 1; index >= 0; index--) {
  24019. if (this.meshes[index].id === id) {
  24020. return this.meshes[index];
  24021. }
  24022. }
  24023. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  24024. if (this.transformNodes[index].id === id) {
  24025. return this.transformNodes[index];
  24026. }
  24027. }
  24028. for (index = this.cameras.length - 1; index >= 0; index--) {
  24029. if (this.cameras[index].id === id) {
  24030. return this.cameras[index];
  24031. }
  24032. }
  24033. for (index = this.lights.length - 1; index >= 0; index--) {
  24034. if (this.lights[index].id === id) {
  24035. return this.lights[index];
  24036. }
  24037. }
  24038. return null;
  24039. };
  24040. Scene.prototype.getNodeByID = function (id) {
  24041. var mesh = this.getMeshByID(id);
  24042. if (mesh) {
  24043. return mesh;
  24044. }
  24045. var light = this.getLightByID(id);
  24046. if (light) {
  24047. return light;
  24048. }
  24049. var camera = this.getCameraByID(id);
  24050. if (camera) {
  24051. return camera;
  24052. }
  24053. var bone = this.getBoneByID(id);
  24054. return bone;
  24055. };
  24056. Scene.prototype.getNodeByName = function (name) {
  24057. var mesh = this.getMeshByName(name);
  24058. if (mesh) {
  24059. return mesh;
  24060. }
  24061. var light = this.getLightByName(name);
  24062. if (light) {
  24063. return light;
  24064. }
  24065. var camera = this.getCameraByName(name);
  24066. if (camera) {
  24067. return camera;
  24068. }
  24069. var bone = this.getBoneByName(name);
  24070. return bone;
  24071. };
  24072. Scene.prototype.getMeshByName = function (name) {
  24073. for (var index = 0; index < this.meshes.length; index++) {
  24074. if (this.meshes[index].name === name) {
  24075. return this.meshes[index];
  24076. }
  24077. }
  24078. return null;
  24079. };
  24080. Scene.prototype.getTransformNodeByName = function (name) {
  24081. for (var index = 0; index < this.transformNodes.length; index++) {
  24082. if (this.transformNodes[index].name === name) {
  24083. return this.transformNodes[index];
  24084. }
  24085. }
  24086. return null;
  24087. };
  24088. Scene.prototype.getSoundByName = function (name) {
  24089. var index;
  24090. if (BABYLON.AudioEngine) {
  24091. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  24092. if (this.mainSoundTrack.soundCollection[index].name === name) {
  24093. return this.mainSoundTrack.soundCollection[index];
  24094. }
  24095. }
  24096. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  24097. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  24098. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  24099. return this.soundTracks[sdIndex].soundCollection[index];
  24100. }
  24101. }
  24102. }
  24103. }
  24104. return null;
  24105. };
  24106. Scene.prototype.getLastSkeletonByID = function (id) {
  24107. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  24108. if (this.skeletons[index].id === id) {
  24109. return this.skeletons[index];
  24110. }
  24111. }
  24112. return null;
  24113. };
  24114. Scene.prototype.getSkeletonById = function (id) {
  24115. for (var index = 0; index < this.skeletons.length; index++) {
  24116. if (this.skeletons[index].id === id) {
  24117. return this.skeletons[index];
  24118. }
  24119. }
  24120. return null;
  24121. };
  24122. Scene.prototype.getSkeletonByName = function (name) {
  24123. for (var index = 0; index < this.skeletons.length; index++) {
  24124. if (this.skeletons[index].name === name) {
  24125. return this.skeletons[index];
  24126. }
  24127. }
  24128. return null;
  24129. };
  24130. Scene.prototype.getMorphTargetManagerById = function (id) {
  24131. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  24132. if (this.morphTargetManagers[index].uniqueId === id) {
  24133. return this.morphTargetManagers[index];
  24134. }
  24135. }
  24136. return null;
  24137. };
  24138. Scene.prototype.isActiveMesh = function (mesh) {
  24139. return (this._activeMeshes.indexOf(mesh) !== -1);
  24140. };
  24141. /**
  24142. * Return a the first highlight layer of the scene with a given name.
  24143. * @param name The name of the highlight layer to look for.
  24144. * @return The highlight layer if found otherwise null.
  24145. */
  24146. Scene.prototype.getHighlightLayerByName = function (name) {
  24147. for (var index = 0; index < this.effectLayers.length; index++) {
  24148. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  24149. return this.effectLayers[index];
  24150. }
  24151. }
  24152. return null;
  24153. };
  24154. /**
  24155. * Return a the first highlight layer of the scene with a given name.
  24156. * @param name The name of the highlight layer to look for.
  24157. * @return The highlight layer if found otherwise null.
  24158. */
  24159. Scene.prototype.getGlowLayerByName = function (name) {
  24160. for (var index = 0; index < this.effectLayers.length; index++) {
  24161. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  24162. return this.effectLayers[index];
  24163. }
  24164. }
  24165. return null;
  24166. };
  24167. Object.defineProperty(Scene.prototype, "uid", {
  24168. /**
  24169. * Return a unique id as a string which can serve as an identifier for the scene
  24170. */
  24171. get: function () {
  24172. if (!this._uid) {
  24173. this._uid = BABYLON.Tools.RandomId();
  24174. }
  24175. return this._uid;
  24176. },
  24177. enumerable: true,
  24178. configurable: true
  24179. });
  24180. /**
  24181. * Add an externaly attached data from its key.
  24182. * This method call will fail and return false, if such key already exists.
  24183. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  24184. * @param key the unique key that identifies the data
  24185. * @param data the data object to associate to the key for this Engine instance
  24186. * @return true if no such key were already present and the data was added successfully, false otherwise
  24187. */
  24188. Scene.prototype.addExternalData = function (key, data) {
  24189. if (!this._externalData) {
  24190. this._externalData = new BABYLON.StringDictionary();
  24191. }
  24192. return this._externalData.add(key, data);
  24193. };
  24194. /**
  24195. * Get an externaly attached data from its key
  24196. * @param key the unique key that identifies the data
  24197. * @return the associated data, if present (can be null), or undefined if not present
  24198. */
  24199. Scene.prototype.getExternalData = function (key) {
  24200. if (!this._externalData) {
  24201. return null;
  24202. }
  24203. return this._externalData.get(key);
  24204. };
  24205. /**
  24206. * Get an externaly attached data from its key, create it using a factory if it's not already present
  24207. * @param key the unique key that identifies the data
  24208. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  24209. * @return the associated data, can be null if the factory returned null.
  24210. */
  24211. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  24212. if (!this._externalData) {
  24213. this._externalData = new BABYLON.StringDictionary();
  24214. }
  24215. return this._externalData.getOrAddWithFactory(key, factory);
  24216. };
  24217. /**
  24218. * Remove an externaly attached data from the Engine instance
  24219. * @param key the unique key that identifies the data
  24220. * @return true if the data was successfully removed, false if it doesn't exist
  24221. */
  24222. Scene.prototype.removeExternalData = function (key) {
  24223. return this._externalData.remove(key);
  24224. };
  24225. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  24226. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  24227. if (mesh.showSubMeshesBoundingBox) {
  24228. var boundingInfo = subMesh.getBoundingInfo();
  24229. if (boundingInfo !== null && boundingInfo !== undefined) {
  24230. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24231. }
  24232. }
  24233. var material = subMesh.getMaterial();
  24234. if (material !== null && material !== undefined) {
  24235. // Render targets
  24236. if (material.getRenderTargetTextures !== undefined) {
  24237. if (this._processedMaterials.indexOf(material) === -1) {
  24238. this._processedMaterials.push(material);
  24239. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  24240. }
  24241. }
  24242. // Dispatch
  24243. this._activeIndices.addCount(subMesh.indexCount, false);
  24244. this._renderingManager.dispatch(subMesh, mesh, material);
  24245. }
  24246. }
  24247. };
  24248. /**
  24249. * Clear the processed materials smart array preventing retention point in material dispose.
  24250. */
  24251. Scene.prototype.freeProcessedMaterials = function () {
  24252. this._processedMaterials.dispose();
  24253. };
  24254. /**
  24255. * Clear the active meshes smart array preventing retention point in mesh dispose.
  24256. */
  24257. Scene.prototype.freeActiveMeshes = function () {
  24258. this._activeMeshes.dispose();
  24259. if (this.activeCamera && this.activeCamera._activeMeshes) {
  24260. this.activeCamera._activeMeshes.dispose();
  24261. }
  24262. if (this.activeCameras) {
  24263. for (var i = 0; i < this.activeCameras.length; i++) {
  24264. var activeCamera = this.activeCameras[i];
  24265. if (activeCamera && activeCamera._activeMeshes) {
  24266. activeCamera._activeMeshes.dispose();
  24267. }
  24268. }
  24269. }
  24270. };
  24271. /**
  24272. * Clear the info related to rendering groups preventing retention points during dispose.
  24273. */
  24274. Scene.prototype.freeRenderingGroups = function () {
  24275. if (this._renderingManager) {
  24276. this._renderingManager.freeRenderingGroups();
  24277. }
  24278. if (this.textures) {
  24279. for (var i = 0; i < this.textures.length; i++) {
  24280. var texture = this.textures[i];
  24281. if (texture && texture.renderList) {
  24282. texture.freeRenderingGroups();
  24283. }
  24284. }
  24285. }
  24286. };
  24287. Scene.prototype._isInIntermediateRendering = function () {
  24288. return this._intermediateRendering;
  24289. };
  24290. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  24291. this._activeMeshCandidateProvider = provider;
  24292. };
  24293. Scene.prototype.getActiveMeshCandidateProvider = function () {
  24294. return this._activeMeshCandidateProvider;
  24295. };
  24296. /**
  24297. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  24298. */
  24299. Scene.prototype.freezeActiveMeshes = function () {
  24300. if (!this.activeCamera) {
  24301. return this;
  24302. }
  24303. if (!this._frustumPlanes) {
  24304. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24305. }
  24306. this._evaluateActiveMeshes();
  24307. this._activeMeshesFrozen = true;
  24308. return this;
  24309. };
  24310. /**
  24311. * Use this function to restart evaluating active meshes on every frame
  24312. */
  24313. Scene.prototype.unfreezeActiveMeshes = function () {
  24314. this._activeMeshesFrozen = false;
  24315. return this;
  24316. };
  24317. Scene.prototype._evaluateActiveMeshes = function () {
  24318. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  24319. return;
  24320. }
  24321. if (!this.activeCamera) {
  24322. return;
  24323. }
  24324. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  24325. this.activeCamera._activeMeshes.reset();
  24326. this._activeMeshes.reset();
  24327. this._renderingManager.reset();
  24328. this._processedMaterials.reset();
  24329. this._activeParticleSystems.reset();
  24330. this._activeSkeletons.reset();
  24331. this._softwareSkinnedMeshes.reset();
  24332. if (this._boundingBoxRenderer) {
  24333. this._boundingBoxRenderer.reset();
  24334. }
  24335. // Meshes
  24336. var meshes;
  24337. var len;
  24338. var checkIsEnabled = true;
  24339. // Determine mesh candidates
  24340. if (this._activeMeshCandidateProvider !== undefined) {
  24341. // Use _activeMeshCandidateProvider
  24342. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  24343. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  24344. if (meshes !== undefined) {
  24345. len = meshes.length;
  24346. }
  24347. else {
  24348. len = 0;
  24349. }
  24350. }
  24351. else if (this._selectionOctree !== undefined) {
  24352. // Octree
  24353. var selection = this._selectionOctree.select(this._frustumPlanes);
  24354. meshes = selection.data;
  24355. len = selection.length;
  24356. }
  24357. else {
  24358. // Full scene traversal
  24359. len = this.meshes.length;
  24360. meshes = this.meshes;
  24361. }
  24362. // Check each mesh
  24363. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  24364. mesh = meshes[meshIndex];
  24365. if (mesh.isBlocked) {
  24366. continue;
  24367. }
  24368. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  24369. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  24370. continue;
  24371. }
  24372. mesh.computeWorldMatrix();
  24373. // Intersections
  24374. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  24375. this._meshesForIntersections.pushNoDuplicate(mesh);
  24376. }
  24377. // Switch to current LOD
  24378. meshLOD = mesh.getLOD(this.activeCamera);
  24379. if (meshLOD === undefined || meshLOD === null) {
  24380. continue;
  24381. }
  24382. mesh._preActivate();
  24383. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  24384. this._activeMeshes.push(mesh);
  24385. this.activeCamera._activeMeshes.push(mesh);
  24386. mesh._activate(this._renderId);
  24387. if (meshLOD !== mesh) {
  24388. meshLOD._activate(this._renderId);
  24389. }
  24390. this._activeMesh(mesh, meshLOD);
  24391. }
  24392. }
  24393. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  24394. // Particle systems
  24395. if (this.particlesEnabled) {
  24396. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  24397. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  24398. var particleSystem = this.particleSystems[particleIndex];
  24399. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  24400. continue;
  24401. }
  24402. var emitter = particleSystem.emitter;
  24403. if (!emitter.position || emitter.isEnabled()) {
  24404. this._activeParticleSystems.push(particleSystem);
  24405. particleSystem.animate();
  24406. this._renderingManager.dispatchParticles(particleSystem);
  24407. }
  24408. }
  24409. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  24410. }
  24411. };
  24412. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  24413. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  24414. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  24415. mesh.skeleton.prepare();
  24416. }
  24417. if (!mesh.computeBonesUsingShaders) {
  24418. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  24419. }
  24420. }
  24421. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  24422. var boundingInfo = sourceMesh.getBoundingInfo();
  24423. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24424. }
  24425. if (mesh !== undefined && mesh !== null
  24426. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  24427. // Submeshes Octrees
  24428. var len;
  24429. var subMeshes;
  24430. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  24431. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  24432. len = intersections.length;
  24433. subMeshes = intersections.data;
  24434. }
  24435. else {
  24436. subMeshes = mesh.subMeshes;
  24437. len = subMeshes.length;
  24438. }
  24439. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  24440. subMesh = subMeshes[subIndex];
  24441. this._evaluateSubMesh(subMesh, mesh);
  24442. }
  24443. }
  24444. };
  24445. Scene.prototype.updateTransformMatrix = function (force) {
  24446. if (!this.activeCamera) {
  24447. return;
  24448. }
  24449. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  24450. };
  24451. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  24452. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  24453. };
  24454. Scene.prototype._renderForCamera = function (camera, rigParent) {
  24455. if (camera && camera._skipRendering) {
  24456. return;
  24457. }
  24458. var engine = this._engine;
  24459. this.activeCamera = camera;
  24460. if (!this.activeCamera)
  24461. throw new Error("Active camera not set");
  24462. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24463. // Viewport
  24464. engine.setViewport(this.activeCamera.viewport);
  24465. // Camera
  24466. this.resetCachedMaterial();
  24467. this._renderId++;
  24468. this.updateTransformMatrix();
  24469. if (camera._alternateCamera) {
  24470. this.updateAlternateTransformMatrix(camera._alternateCamera);
  24471. this._alternateRendering = true;
  24472. }
  24473. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  24474. // Meshes
  24475. this._evaluateActiveMeshes();
  24476. // Software skinning
  24477. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  24478. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  24479. mesh.applySkeleton(mesh.skeleton);
  24480. }
  24481. // Render targets
  24482. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24483. var needsRestoreFrameBuffer = false;
  24484. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  24485. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  24486. }
  24487. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  24488. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  24489. }
  24490. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  24491. this._intermediateRendering = true;
  24492. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24493. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24494. var renderTarget = this._renderTargets.data[renderIndex];
  24495. if (renderTarget._shouldRender()) {
  24496. this._renderId++;
  24497. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24498. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24499. }
  24500. }
  24501. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24502. this._intermediateRendering = false;
  24503. this._renderId++;
  24504. needsRestoreFrameBuffer = true; // Restore back buffer
  24505. }
  24506. // Render EffecttLayer Texture
  24507. var stencilState = this._engine.getStencilBuffer();
  24508. var renderEffects = false;
  24509. var needStencil = false;
  24510. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24511. this._intermediateRendering = true;
  24512. for (var i = 0; i < this.effectLayers.length; i++) {
  24513. var effectLayer = this.effectLayers[i];
  24514. if (effectLayer.shouldRender() &&
  24515. (!effectLayer.camera ||
  24516. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24517. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24518. renderEffects = true;
  24519. needStencil = needStencil || effectLayer.needStencil();
  24520. var renderTarget = effectLayer._mainTexture;
  24521. if (renderTarget._shouldRender()) {
  24522. this._renderId++;
  24523. renderTarget.render(false, false);
  24524. needsRestoreFrameBuffer = true;
  24525. }
  24526. }
  24527. }
  24528. this._intermediateRendering = false;
  24529. this._renderId++;
  24530. }
  24531. if (needsRestoreFrameBuffer) {
  24532. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24533. }
  24534. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24535. // Prepare Frame
  24536. this.postProcessManager._prepareFrame();
  24537. // Backgrounds
  24538. var layerIndex;
  24539. var layer;
  24540. if (this.layers.length) {
  24541. engine.setDepthBuffer(false);
  24542. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24543. layer = this.layers[layerIndex];
  24544. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24545. layer.render();
  24546. }
  24547. }
  24548. engine.setDepthBuffer(true);
  24549. }
  24550. // Activate effect Layer stencil
  24551. if (needStencil) {
  24552. this._engine.setStencilBuffer(true);
  24553. }
  24554. // Render
  24555. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24556. this._renderingManager.render(null, null, true, true);
  24557. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24558. // Restore effect Layer stencil
  24559. if (needStencil) {
  24560. this._engine.setStencilBuffer(stencilState);
  24561. }
  24562. // Bounding boxes
  24563. if (this._boundingBoxRenderer) {
  24564. this._boundingBoxRenderer.render();
  24565. }
  24566. // Lens flares
  24567. if (this.lensFlaresEnabled) {
  24568. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24569. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24570. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24571. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24572. lensFlareSystem.render();
  24573. }
  24574. }
  24575. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24576. }
  24577. // Foregrounds
  24578. if (this.layers.length) {
  24579. engine.setDepthBuffer(false);
  24580. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24581. layer = this.layers[layerIndex];
  24582. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24583. layer.render();
  24584. }
  24585. }
  24586. engine.setDepthBuffer(true);
  24587. }
  24588. // Effect Layer
  24589. if (renderEffects) {
  24590. engine.setDepthBuffer(false);
  24591. for (var i = 0; i < this.effectLayers.length; i++) {
  24592. if (this.effectLayers[i].shouldRender()) {
  24593. this.effectLayers[i].render();
  24594. }
  24595. }
  24596. engine.setDepthBuffer(true);
  24597. }
  24598. // Finalize frame
  24599. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24600. // Reset some special arrays
  24601. this._renderTargets.reset();
  24602. this._alternateRendering = false;
  24603. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24604. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24605. };
  24606. Scene.prototype._processSubCameras = function (camera) {
  24607. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24608. this._renderForCamera(camera);
  24609. return;
  24610. }
  24611. // rig cameras
  24612. for (var index = 0; index < camera._rigCameras.length; index++) {
  24613. this._renderForCamera(camera._rigCameras[index], camera);
  24614. }
  24615. this.activeCamera = camera;
  24616. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24617. };
  24618. Scene.prototype._checkIntersections = function () {
  24619. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24620. var sourceMesh = this._meshesForIntersections.data[index];
  24621. if (!sourceMesh.actionManager) {
  24622. continue;
  24623. }
  24624. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24625. var action = sourceMesh.actionManager.actions[actionIndex];
  24626. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24627. var parameters = action.getTriggerParameter();
  24628. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24629. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24630. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24631. if (areIntersecting && currentIntersectionInProgress === -1) {
  24632. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24633. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24634. sourceMesh._intersectionsInProgress.push(otherMesh);
  24635. }
  24636. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24637. sourceMesh._intersectionsInProgress.push(otherMesh);
  24638. }
  24639. }
  24640. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24641. //They intersected, and now they don't.
  24642. //is this trigger an exit trigger? execute an event.
  24643. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24644. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24645. }
  24646. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24647. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24648. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24649. }
  24650. }
  24651. }
  24652. }
  24653. }
  24654. };
  24655. Scene.prototype.render = function () {
  24656. if (this.isDisposed) {
  24657. return;
  24658. }
  24659. this._activeParticles.fetchNewFrame();
  24660. this._totalVertices.fetchNewFrame();
  24661. this._activeIndices.fetchNewFrame();
  24662. this._activeBones.fetchNewFrame();
  24663. this._meshesForIntersections.reset();
  24664. this.resetCachedMaterial();
  24665. this.onBeforeAnimationsObservable.notifyObservers(this);
  24666. // Actions
  24667. if (this.actionManager) {
  24668. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24669. }
  24670. //Simplification Queue
  24671. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24672. this.simplificationQueue.executeNext();
  24673. }
  24674. if (this._engine.isDeterministicLockStep()) {
  24675. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24676. var defaultFPS = (60.0 / 1000.0);
  24677. var defaultFrameTime = 1000 / 60; // frame time in MS
  24678. if (this._physicsEngine) {
  24679. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24680. }
  24681. var stepsTaken = 0;
  24682. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24683. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24684. internalSteps = Math.min(internalSteps, maxSubSteps);
  24685. do {
  24686. this.onBeforeStepObservable.notifyObservers(this);
  24687. // Animations
  24688. this._animationRatio = defaultFrameTime * defaultFPS;
  24689. this._animate();
  24690. this.onAfterAnimationsObservable.notifyObservers(this);
  24691. // Physics
  24692. if (this._physicsEngine) {
  24693. this.onBeforePhysicsObservable.notifyObservers(this);
  24694. this._physicsEngine._step(defaultFrameTime / 1000);
  24695. this.onAfterPhysicsObservable.notifyObservers(this);
  24696. }
  24697. this.onAfterStepObservable.notifyObservers(this);
  24698. this._currentStepId++;
  24699. stepsTaken++;
  24700. deltaTime -= defaultFrameTime;
  24701. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24702. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24703. }
  24704. else {
  24705. // Animations
  24706. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24707. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24708. this._animate();
  24709. this.onAfterAnimationsObservable.notifyObservers(this);
  24710. // Physics
  24711. if (this._physicsEngine) {
  24712. this.onBeforePhysicsObservable.notifyObservers(this);
  24713. this._physicsEngine._step(deltaTime / 1000.0);
  24714. this.onAfterPhysicsObservable.notifyObservers(this);
  24715. }
  24716. }
  24717. // update gamepad manager
  24718. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24719. this._gamepadManager._checkGamepadsStatus();
  24720. }
  24721. // Update Cameras
  24722. if (this.activeCameras.length > 0) {
  24723. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24724. var camera = this.activeCameras[cameraIndex];
  24725. camera.update();
  24726. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24727. // rig cameras
  24728. for (var index = 0; index < camera._rigCameras.length; index++) {
  24729. camera._rigCameras[index].update();
  24730. }
  24731. }
  24732. }
  24733. }
  24734. else if (this.activeCamera) {
  24735. this.activeCamera.update();
  24736. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24737. // rig cameras
  24738. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24739. this.activeCamera._rigCameras[index].update();
  24740. }
  24741. }
  24742. }
  24743. // Before render
  24744. this.onBeforeRenderObservable.notifyObservers(this);
  24745. // Customs render targets
  24746. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24747. var engine = this.getEngine();
  24748. var currentActiveCamera = this.activeCamera;
  24749. if (this.renderTargetsEnabled) {
  24750. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24751. this._intermediateRendering = true;
  24752. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24753. var renderTarget = this.customRenderTargets[customIndex];
  24754. if (renderTarget._shouldRender()) {
  24755. this._renderId++;
  24756. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24757. if (!this.activeCamera)
  24758. throw new Error("Active camera not set");
  24759. // Viewport
  24760. engine.setViewport(this.activeCamera.viewport);
  24761. // Camera
  24762. this.updateTransformMatrix();
  24763. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24764. }
  24765. }
  24766. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24767. this._intermediateRendering = false;
  24768. this._renderId++;
  24769. }
  24770. // Restore back buffer
  24771. if (this.customRenderTargets.length > 0) {
  24772. engine.restoreDefaultFramebuffer();
  24773. }
  24774. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24775. this.activeCamera = currentActiveCamera;
  24776. // Procedural textures
  24777. if (this.proceduralTexturesEnabled) {
  24778. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24779. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24780. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24781. if (proceduralTexture._shouldRender()) {
  24782. proceduralTexture.render();
  24783. }
  24784. }
  24785. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24786. }
  24787. // Clear
  24788. if (this.autoClearDepthAndStencil || this.autoClear) {
  24789. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24790. }
  24791. // Shadows
  24792. if (this.shadowsEnabled) {
  24793. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24794. var light = this.lights[lightIndex];
  24795. var shadowGenerator = light.getShadowGenerator();
  24796. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24797. var shadowMap = (shadowGenerator.getShadowMap());
  24798. if (this.textures.indexOf(shadowMap) !== -1) {
  24799. this._renderTargets.push(shadowMap);
  24800. }
  24801. }
  24802. }
  24803. }
  24804. // Depth renderer
  24805. for (var key in this._depthRenderer) {
  24806. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24807. }
  24808. // Geometry renderer
  24809. if (this._geometryBufferRenderer) {
  24810. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24811. }
  24812. // RenderPipeline
  24813. if (this._postProcessRenderPipelineManager) {
  24814. this._postProcessRenderPipelineManager.update();
  24815. }
  24816. // Multi-cameras?
  24817. if (this.activeCameras.length > 0) {
  24818. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24819. if (cameraIndex > 0) {
  24820. this._engine.clear(null, false, true, true);
  24821. }
  24822. this._processSubCameras(this.activeCameras[cameraIndex]);
  24823. }
  24824. }
  24825. else {
  24826. if (!this.activeCamera) {
  24827. throw new Error("No camera defined");
  24828. }
  24829. this._processSubCameras(this.activeCamera);
  24830. }
  24831. // Intersection checks
  24832. this._checkIntersections();
  24833. // Update the audio listener attached to the camera
  24834. if (BABYLON.AudioEngine) {
  24835. this._updateAudioParameters();
  24836. }
  24837. // After render
  24838. if (this.afterRender) {
  24839. this.afterRender();
  24840. }
  24841. this.onAfterRenderObservable.notifyObservers(this);
  24842. // Cleaning
  24843. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24844. var data = this._toBeDisposed.data[index];
  24845. if (data) {
  24846. data.dispose();
  24847. }
  24848. this._toBeDisposed[index] = null;
  24849. }
  24850. this._toBeDisposed.reset();
  24851. if (this.dumpNextRenderTargets) {
  24852. this.dumpNextRenderTargets = false;
  24853. }
  24854. this._activeBones.addCount(0, true);
  24855. this._activeIndices.addCount(0, true);
  24856. this._activeParticles.addCount(0, true);
  24857. };
  24858. Scene.prototype._updateAudioParameters = function () {
  24859. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24860. return;
  24861. }
  24862. var listeningCamera;
  24863. var audioEngine = BABYLON.Engine.audioEngine;
  24864. if (this.activeCameras.length > 0) {
  24865. listeningCamera = this.activeCameras[0];
  24866. }
  24867. else {
  24868. listeningCamera = this.activeCamera;
  24869. }
  24870. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24871. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24872. // for VR cameras
  24873. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24874. listeningCamera = listeningCamera.rigCameras[0];
  24875. }
  24876. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24877. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24878. cameraDirection.normalize();
  24879. // To avoid some errors on GearVR
  24880. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24881. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24882. }
  24883. var i;
  24884. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24885. var sound = this.mainSoundTrack.soundCollection[i];
  24886. if (sound.useCustomAttenuation) {
  24887. sound.updateDistanceFromListener();
  24888. }
  24889. }
  24890. for (i = 0; i < this.soundTracks.length; i++) {
  24891. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24892. sound = this.soundTracks[i].soundCollection[j];
  24893. if (sound.useCustomAttenuation) {
  24894. sound.updateDistanceFromListener();
  24895. }
  24896. }
  24897. }
  24898. }
  24899. };
  24900. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24901. // Audio
  24902. get: function () {
  24903. return this._audioEnabled;
  24904. },
  24905. set: function (value) {
  24906. this._audioEnabled = value;
  24907. if (BABYLON.AudioEngine) {
  24908. if (this._audioEnabled) {
  24909. this._enableAudio();
  24910. }
  24911. else {
  24912. this._disableAudio();
  24913. }
  24914. }
  24915. },
  24916. enumerable: true,
  24917. configurable: true
  24918. });
  24919. Scene.prototype._disableAudio = function () {
  24920. var i;
  24921. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24922. this.mainSoundTrack.soundCollection[i].pause();
  24923. }
  24924. for (i = 0; i < this.soundTracks.length; i++) {
  24925. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24926. this.soundTracks[i].soundCollection[j].pause();
  24927. }
  24928. }
  24929. };
  24930. Scene.prototype._enableAudio = function () {
  24931. var i;
  24932. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24933. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  24934. this.mainSoundTrack.soundCollection[i].play();
  24935. }
  24936. }
  24937. for (i = 0; i < this.soundTracks.length; i++) {
  24938. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24939. if (this.soundTracks[i].soundCollection[j].isPaused) {
  24940. this.soundTracks[i].soundCollection[j].play();
  24941. }
  24942. }
  24943. }
  24944. };
  24945. Object.defineProperty(Scene.prototype, "headphone", {
  24946. get: function () {
  24947. return this._headphone;
  24948. },
  24949. set: function (value) {
  24950. this._headphone = value;
  24951. if (BABYLON.AudioEngine) {
  24952. if (this._headphone) {
  24953. this._switchAudioModeForHeadphones();
  24954. }
  24955. else {
  24956. this._switchAudioModeForNormalSpeakers();
  24957. }
  24958. }
  24959. },
  24960. enumerable: true,
  24961. configurable: true
  24962. });
  24963. Scene.prototype._switchAudioModeForHeadphones = function () {
  24964. this.mainSoundTrack.switchPanningModelToHRTF();
  24965. for (var i = 0; i < this.soundTracks.length; i++) {
  24966. this.soundTracks[i].switchPanningModelToHRTF();
  24967. }
  24968. };
  24969. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  24970. this.mainSoundTrack.switchPanningModelToEqualPower();
  24971. for (var i = 0; i < this.soundTracks.length; i++) {
  24972. this.soundTracks[i].switchPanningModelToEqualPower();
  24973. }
  24974. };
  24975. /**
  24976. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  24977. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  24978. * @returns the created depth renderer
  24979. */
  24980. Scene.prototype.enableDepthRenderer = function (camera) {
  24981. camera = camera || this.activeCamera;
  24982. if (!camera) {
  24983. throw "No camera available to enable depth renderer";
  24984. }
  24985. if (!this._depthRenderer[camera.id]) {
  24986. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, BABYLON.Engine.TEXTURETYPE_FLOAT, camera);
  24987. }
  24988. return this._depthRenderer[camera.id];
  24989. };
  24990. /**
  24991. * Disables a depth renderer for a given camera
  24992. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  24993. */
  24994. Scene.prototype.disableDepthRenderer = function (camera) {
  24995. camera = camera || this.activeCamera;
  24996. if (!camera || !this._depthRenderer[camera.id]) {
  24997. return;
  24998. }
  24999. this._depthRenderer[camera.id].dispose();
  25000. delete this._depthRenderer[camera.id];
  25001. };
  25002. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  25003. if (ratio === void 0) { ratio = 1; }
  25004. if (this._geometryBufferRenderer) {
  25005. return this._geometryBufferRenderer;
  25006. }
  25007. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  25008. if (!this._geometryBufferRenderer.isSupported) {
  25009. this._geometryBufferRenderer = null;
  25010. }
  25011. return this._geometryBufferRenderer;
  25012. };
  25013. Scene.prototype.disableGeometryBufferRenderer = function () {
  25014. if (!this._geometryBufferRenderer) {
  25015. return;
  25016. }
  25017. this._geometryBufferRenderer.dispose();
  25018. this._geometryBufferRenderer = null;
  25019. };
  25020. Scene.prototype.freezeMaterials = function () {
  25021. for (var i = 0; i < this.materials.length; i++) {
  25022. this.materials[i].freeze();
  25023. }
  25024. };
  25025. Scene.prototype.unfreezeMaterials = function () {
  25026. for (var i = 0; i < this.materials.length; i++) {
  25027. this.materials[i].unfreeze();
  25028. }
  25029. };
  25030. Scene.prototype.dispose = function () {
  25031. this.beforeRender = null;
  25032. this.afterRender = null;
  25033. this.skeletons = [];
  25034. this.morphTargetManagers = [];
  25035. this.importedMeshesFiles = new Array();
  25036. this.stopAllAnimations();
  25037. this.resetCachedMaterial();
  25038. for (var key in this._depthRenderer) {
  25039. this._depthRenderer[key].dispose();
  25040. }
  25041. if (this._gamepadManager) {
  25042. this._gamepadManager.dispose();
  25043. this._gamepadManager = null;
  25044. }
  25045. // Smart arrays
  25046. if (this.activeCamera) {
  25047. this.activeCamera._activeMeshes.dispose();
  25048. this.activeCamera = null;
  25049. }
  25050. this._activeMeshes.dispose();
  25051. this._renderingManager.dispose();
  25052. this._processedMaterials.dispose();
  25053. this._activeParticleSystems.dispose();
  25054. this._activeSkeletons.dispose();
  25055. this._softwareSkinnedMeshes.dispose();
  25056. this._renderTargets.dispose();
  25057. this._registeredForLateAnimationBindings.dispose();
  25058. if (this._boundingBoxRenderer) {
  25059. this._boundingBoxRenderer.dispose();
  25060. }
  25061. this._meshesForIntersections.dispose();
  25062. this._toBeDisposed.dispose();
  25063. // Abort active requests
  25064. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  25065. var request = _a[_i];
  25066. request.abort();
  25067. }
  25068. // Debug layer
  25069. if (this._debugLayer) {
  25070. this._debugLayer.hide();
  25071. }
  25072. // Events
  25073. this.onDisposeObservable.notifyObservers(this);
  25074. this.onDisposeObservable.clear();
  25075. this.onBeforeRenderObservable.clear();
  25076. this.onAfterRenderObservable.clear();
  25077. this.OnBeforeRenderTargetsRenderObservable.clear();
  25078. this.OnAfterRenderTargetsRenderObservable.clear();
  25079. this.onAfterStepObservable.clear();
  25080. this.onBeforeStepObservable.clear();
  25081. this.onBeforeActiveMeshesEvaluationObservable.clear();
  25082. this.onAfterActiveMeshesEvaluationObservable.clear();
  25083. this.onBeforeParticlesRenderingObservable.clear();
  25084. this.onAfterParticlesRenderingObservable.clear();
  25085. this.onBeforeSpritesRenderingObservable.clear();
  25086. this.onAfterSpritesRenderingObservable.clear();
  25087. this.onBeforeDrawPhaseObservable.clear();
  25088. this.onAfterDrawPhaseObservable.clear();
  25089. this.onBeforePhysicsObservable.clear();
  25090. this.onAfterPhysicsObservable.clear();
  25091. this.onBeforeAnimationsObservable.clear();
  25092. this.onAfterAnimationsObservable.clear();
  25093. this.onDataLoadedObservable.clear();
  25094. this.detachControl();
  25095. // Release sounds & sounds tracks
  25096. if (BABYLON.AudioEngine) {
  25097. this.disposeSounds();
  25098. }
  25099. // VR Helper
  25100. if (this.VRHelper) {
  25101. this.VRHelper.dispose();
  25102. }
  25103. // Detach cameras
  25104. var canvas = this._engine.getRenderingCanvas();
  25105. if (canvas) {
  25106. var index;
  25107. for (index = 0; index < this.cameras.length; index++) {
  25108. this.cameras[index].detachControl(canvas);
  25109. }
  25110. }
  25111. // Release animation groups
  25112. while (this.animationGroups.length) {
  25113. this.animationGroups[0].dispose();
  25114. }
  25115. // Release lights
  25116. while (this.lights.length) {
  25117. this.lights[0].dispose();
  25118. }
  25119. // Release meshes
  25120. while (this.meshes.length) {
  25121. this.meshes[0].dispose(true);
  25122. }
  25123. while (this.transformNodes.length) {
  25124. this.removeTransformNode(this.transformNodes[0]);
  25125. }
  25126. // Release cameras
  25127. while (this.cameras.length) {
  25128. this.cameras[0].dispose();
  25129. }
  25130. // Release materials
  25131. if (this.defaultMaterial) {
  25132. this.defaultMaterial.dispose();
  25133. }
  25134. while (this.multiMaterials.length) {
  25135. this.multiMaterials[0].dispose();
  25136. }
  25137. while (this.materials.length) {
  25138. this.materials[0].dispose();
  25139. }
  25140. // Release particles
  25141. while (this.particleSystems.length) {
  25142. this.particleSystems[0].dispose();
  25143. }
  25144. // Release sprites
  25145. while (this.spriteManagers.length) {
  25146. this.spriteManagers[0].dispose();
  25147. }
  25148. // Release postProcesses
  25149. while (this.postProcesses.length) {
  25150. this.postProcesses[0].dispose();
  25151. }
  25152. // Release layers
  25153. while (this.layers.length) {
  25154. this.layers[0].dispose();
  25155. }
  25156. while (this.effectLayers.length) {
  25157. this.effectLayers[0].dispose();
  25158. }
  25159. // Release textures
  25160. while (this.textures.length) {
  25161. this.textures[0].dispose();
  25162. }
  25163. // Release UBO
  25164. this._sceneUbo.dispose();
  25165. if (this._alternateSceneUbo) {
  25166. this._alternateSceneUbo.dispose();
  25167. }
  25168. // Post-processes
  25169. this.postProcessManager.dispose();
  25170. if (this._postProcessRenderPipelineManager) {
  25171. this._postProcessRenderPipelineManager.dispose();
  25172. }
  25173. // Physics
  25174. if (this._physicsEngine) {
  25175. this.disablePhysicsEngine();
  25176. }
  25177. // Remove from engine
  25178. index = this._engine.scenes.indexOf(this);
  25179. if (index > -1) {
  25180. this._engine.scenes.splice(index, 1);
  25181. }
  25182. this._engine.wipeCaches(true);
  25183. this._isDisposed = true;
  25184. };
  25185. Object.defineProperty(Scene.prototype, "isDisposed", {
  25186. get: function () {
  25187. return this._isDisposed;
  25188. },
  25189. enumerable: true,
  25190. configurable: true
  25191. });
  25192. // Release sounds & sounds tracks
  25193. Scene.prototype.disposeSounds = function () {
  25194. if (!this._mainSoundTrack) {
  25195. return;
  25196. }
  25197. this.mainSoundTrack.dispose();
  25198. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  25199. this.soundTracks[scIndex].dispose();
  25200. }
  25201. };
  25202. // Octrees
  25203. /**
  25204. * Get the world extend vectors with an optional filter
  25205. *
  25206. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  25207. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  25208. */
  25209. Scene.prototype.getWorldExtends = function (filterPredicate) {
  25210. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  25211. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  25212. filterPredicate = filterPredicate || (function () { return true; });
  25213. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  25214. mesh.computeWorldMatrix(true);
  25215. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  25216. return;
  25217. }
  25218. var boundingInfo = mesh.getBoundingInfo();
  25219. var minBox = boundingInfo.boundingBox.minimumWorld;
  25220. var maxBox = boundingInfo.boundingBox.maximumWorld;
  25221. BABYLON.Tools.CheckExtends(minBox, min, max);
  25222. BABYLON.Tools.CheckExtends(maxBox, min, max);
  25223. });
  25224. return {
  25225. min: min,
  25226. max: max
  25227. };
  25228. };
  25229. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  25230. if (maxCapacity === void 0) { maxCapacity = 64; }
  25231. if (maxDepth === void 0) { maxDepth = 2; }
  25232. if (!this._selectionOctree) {
  25233. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  25234. }
  25235. var worldExtends = this.getWorldExtends();
  25236. // Update octree
  25237. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  25238. return this._selectionOctree;
  25239. };
  25240. // Picking
  25241. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  25242. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25243. var result = BABYLON.Ray.Zero();
  25244. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  25245. return result;
  25246. };
  25247. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  25248. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25249. var engine = this._engine;
  25250. if (!camera) {
  25251. if (!this.activeCamera)
  25252. throw new Error("Active camera not set");
  25253. camera = this.activeCamera;
  25254. }
  25255. var cameraViewport = camera.viewport;
  25256. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25257. // Moving coordinates to local viewport world
  25258. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25259. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25260. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  25261. return this;
  25262. };
  25263. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  25264. var result = BABYLON.Ray.Zero();
  25265. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  25266. return result;
  25267. };
  25268. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  25269. if (!BABYLON.PickingInfo) {
  25270. return this;
  25271. }
  25272. var engine = this._engine;
  25273. if (!camera) {
  25274. if (!this.activeCamera)
  25275. throw new Error("Active camera not set");
  25276. camera = this.activeCamera;
  25277. }
  25278. var cameraViewport = camera.viewport;
  25279. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25280. var identity = BABYLON.Matrix.Identity();
  25281. // Moving coordinates to local viewport world
  25282. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25283. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25284. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  25285. return this;
  25286. };
  25287. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  25288. if (!BABYLON.PickingInfo) {
  25289. return null;
  25290. }
  25291. var pickingInfo = null;
  25292. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25293. var mesh = this.meshes[meshIndex];
  25294. if (predicate) {
  25295. if (!predicate(mesh)) {
  25296. continue;
  25297. }
  25298. }
  25299. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25300. continue;
  25301. }
  25302. var world = mesh.getWorldMatrix();
  25303. var ray = rayFunction(world);
  25304. var result = mesh.intersects(ray, fastCheck);
  25305. if (!result || !result.hit)
  25306. continue;
  25307. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25308. continue;
  25309. pickingInfo = result;
  25310. if (fastCheck) {
  25311. break;
  25312. }
  25313. }
  25314. return pickingInfo || new BABYLON.PickingInfo();
  25315. };
  25316. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  25317. if (!BABYLON.PickingInfo) {
  25318. return null;
  25319. }
  25320. var pickingInfos = new Array();
  25321. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25322. var mesh = this.meshes[meshIndex];
  25323. if (predicate) {
  25324. if (!predicate(mesh)) {
  25325. continue;
  25326. }
  25327. }
  25328. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25329. continue;
  25330. }
  25331. var world = mesh.getWorldMatrix();
  25332. var ray = rayFunction(world);
  25333. var result = mesh.intersects(ray, false);
  25334. if (!result || !result.hit)
  25335. continue;
  25336. pickingInfos.push(result);
  25337. }
  25338. return pickingInfos;
  25339. };
  25340. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  25341. if (!BABYLON.PickingInfo) {
  25342. return null;
  25343. }
  25344. var pickingInfo = null;
  25345. if (!camera) {
  25346. if (!this.activeCamera) {
  25347. return null;
  25348. }
  25349. camera = this.activeCamera;
  25350. }
  25351. if (this.spriteManagers.length > 0) {
  25352. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  25353. var spriteManager = this.spriteManagers[spriteIndex];
  25354. if (!spriteManager.isPickable) {
  25355. continue;
  25356. }
  25357. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  25358. if (!result || !result.hit)
  25359. continue;
  25360. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25361. continue;
  25362. pickingInfo = result;
  25363. if (fastCheck) {
  25364. break;
  25365. }
  25366. }
  25367. }
  25368. return pickingInfo || new BABYLON.PickingInfo();
  25369. };
  25370. /** Launch a ray to try to pick a mesh in the scene
  25371. * @param x position on screen
  25372. * @param y position on screen
  25373. * @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
  25374. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25375. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25376. */
  25377. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  25378. var _this = this;
  25379. if (!BABYLON.PickingInfo) {
  25380. return null;
  25381. }
  25382. return this._internalPick(function (world) {
  25383. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  25384. return _this._tempPickingRay;
  25385. }, predicate, fastCheck);
  25386. };
  25387. /** Launch a ray to try to pick a sprite in the scene
  25388. * @param x position on screen
  25389. * @param y position on screen
  25390. * @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
  25391. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25392. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25393. */
  25394. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  25395. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  25396. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  25397. };
  25398. /** Use the given ray to pick a mesh in the scene
  25399. * @param ray The ray to use to pick meshes
  25400. * @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
  25401. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25402. */
  25403. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  25404. var _this = this;
  25405. return this._internalPick(function (world) {
  25406. if (!_this._pickWithRayInverseMatrix) {
  25407. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25408. }
  25409. world.invertToRef(_this._pickWithRayInverseMatrix);
  25410. if (!_this._cachedRayForTransform) {
  25411. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25412. }
  25413. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25414. return _this._cachedRayForTransform;
  25415. }, predicate, fastCheck);
  25416. };
  25417. /**
  25418. * Launch a ray to try to pick a mesh in the scene
  25419. * @param x X position on screen
  25420. * @param y Y position on screen
  25421. * @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
  25422. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25423. */
  25424. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  25425. var _this = this;
  25426. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  25427. };
  25428. /**
  25429. * Launch a ray to try to pick a mesh in the scene
  25430. * @param ray Ray to use
  25431. * @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
  25432. */
  25433. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  25434. var _this = this;
  25435. return this._internalMultiPick(function (world) {
  25436. if (!_this._pickWithRayInverseMatrix) {
  25437. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25438. }
  25439. world.invertToRef(_this._pickWithRayInverseMatrix);
  25440. if (!_this._cachedRayForTransform) {
  25441. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25442. }
  25443. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25444. return _this._cachedRayForTransform;
  25445. }, predicate);
  25446. };
  25447. Scene.prototype.setPointerOverMesh = function (mesh) {
  25448. if (this._pointerOverMesh === mesh) {
  25449. return;
  25450. }
  25451. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25452. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25453. }
  25454. this._pointerOverMesh = mesh;
  25455. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25456. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25457. }
  25458. };
  25459. Scene.prototype.getPointerOverMesh = function () {
  25460. return this._pointerOverMesh;
  25461. };
  25462. Scene.prototype.setPointerOverSprite = function (sprite) {
  25463. if (this._pointerOverSprite === sprite) {
  25464. return;
  25465. }
  25466. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25467. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25468. }
  25469. this._pointerOverSprite = sprite;
  25470. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25471. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25472. }
  25473. };
  25474. Scene.prototype.getPointerOverSprite = function () {
  25475. return this._pointerOverSprite;
  25476. };
  25477. // Physics
  25478. Scene.prototype.getPhysicsEngine = function () {
  25479. return this._physicsEngine;
  25480. };
  25481. /**
  25482. * Enables physics to the current scene
  25483. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  25484. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  25485. * @return {boolean} was the physics engine initialized
  25486. */
  25487. Scene.prototype.enablePhysics = function (gravity, plugin) {
  25488. if (gravity === void 0) { gravity = null; }
  25489. if (this._physicsEngine) {
  25490. return true;
  25491. }
  25492. try {
  25493. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  25494. return true;
  25495. }
  25496. catch (e) {
  25497. BABYLON.Tools.Error(e.message);
  25498. return false;
  25499. }
  25500. };
  25501. Scene.prototype.disablePhysicsEngine = function () {
  25502. if (!this._physicsEngine) {
  25503. return;
  25504. }
  25505. this._physicsEngine.dispose();
  25506. this._physicsEngine = null;
  25507. };
  25508. Scene.prototype.isPhysicsEnabled = function () {
  25509. return this._physicsEngine !== undefined;
  25510. };
  25511. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25512. var mesh = compound.parts[0].mesh;
  25513. if (mesh.physicsImpostor) {
  25514. mesh.physicsImpostor.dispose();
  25515. mesh.physicsImpostor = null;
  25516. }
  25517. };
  25518. // Misc.
  25519. Scene.prototype._rebuildGeometries = function () {
  25520. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25521. var geometry = _a[_i];
  25522. geometry._rebuild();
  25523. }
  25524. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25525. var mesh = _c[_b];
  25526. mesh._rebuild();
  25527. }
  25528. if (this.postProcessManager) {
  25529. this.postProcessManager._rebuild();
  25530. }
  25531. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25532. var layer = _e[_d];
  25533. layer._rebuild();
  25534. }
  25535. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25536. var effectLayer = _g[_f];
  25537. effectLayer._rebuild();
  25538. }
  25539. if (this._boundingBoxRenderer) {
  25540. this._boundingBoxRenderer._rebuild();
  25541. }
  25542. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25543. var system = _j[_h];
  25544. system.rebuild();
  25545. }
  25546. if (this._postProcessRenderPipelineManager) {
  25547. this._postProcessRenderPipelineManager._rebuild();
  25548. }
  25549. };
  25550. Scene.prototype._rebuildTextures = function () {
  25551. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25552. var texture = _a[_i];
  25553. texture._rebuild();
  25554. }
  25555. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25556. };
  25557. /**
  25558. * Creates a default light for the scene.
  25559. * @param replace Whether to replace the existing lights in the scene.
  25560. */
  25561. Scene.prototype.createDefaultLight = function (replace) {
  25562. if (replace === void 0) { replace = false; }
  25563. // Dispose existing light in replace mode.
  25564. if (replace) {
  25565. if (this.lights) {
  25566. for (var i = 0; i < this.lights.length; i++) {
  25567. this.lights[i].dispose();
  25568. }
  25569. }
  25570. }
  25571. // Light
  25572. if (this.lights.length === 0) {
  25573. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25574. }
  25575. };
  25576. /**
  25577. * Creates a default camera for the scene.
  25578. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25579. * @param replace Whether to replace the existing active camera in the scene.
  25580. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25581. */
  25582. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25583. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25584. if (replace === void 0) { replace = false; }
  25585. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25586. // Dispose existing camera in replace mode.
  25587. if (replace) {
  25588. if (this.activeCamera) {
  25589. this.activeCamera.dispose();
  25590. this.activeCamera = null;
  25591. }
  25592. }
  25593. // Camera
  25594. if (!this.activeCamera) {
  25595. var worldExtends = this.getWorldExtends();
  25596. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25597. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25598. var camera;
  25599. var radius = worldSize.length() * 1.5;
  25600. // empty scene scenario!
  25601. if (!isFinite(radius)) {
  25602. radius = 1;
  25603. worldCenter.copyFromFloats(0, 0, 0);
  25604. }
  25605. if (createArcRotateCamera) {
  25606. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25607. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25608. arcRotateCamera.wheelPrecision = 100 / radius;
  25609. camera = arcRotateCamera;
  25610. }
  25611. else {
  25612. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25613. freeCamera.setTarget(worldCenter);
  25614. camera = freeCamera;
  25615. }
  25616. camera.minZ = radius * 0.01;
  25617. camera.maxZ = radius * 1000;
  25618. camera.speed = radius * 0.2;
  25619. this.activeCamera = camera;
  25620. var canvas = this.getEngine().getRenderingCanvas();
  25621. if (attachCameraControls && canvas) {
  25622. camera.attachControl(canvas);
  25623. }
  25624. }
  25625. };
  25626. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25627. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25628. if (replace === void 0) { replace = false; }
  25629. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25630. this.createDefaultLight(replace);
  25631. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25632. };
  25633. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25634. if (pbr === void 0) { pbr = false; }
  25635. if (scale === void 0) { scale = 1000; }
  25636. if (blur === void 0) { blur = 0; }
  25637. if (environmentTexture) {
  25638. this.environmentTexture = environmentTexture;
  25639. }
  25640. if (!this.environmentTexture) {
  25641. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25642. return null;
  25643. }
  25644. // Skybox
  25645. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25646. if (pbr) {
  25647. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25648. hdrSkyboxMaterial.backFaceCulling = false;
  25649. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25650. if (hdrSkyboxMaterial.reflectionTexture) {
  25651. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25652. }
  25653. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25654. hdrSkyboxMaterial.disableLighting = true;
  25655. hdrSkyboxMaterial.twoSidedLighting = true;
  25656. hdrSkybox.infiniteDistance = true;
  25657. hdrSkybox.material = hdrSkyboxMaterial;
  25658. }
  25659. else {
  25660. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25661. skyboxMaterial.backFaceCulling = false;
  25662. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25663. if (skyboxMaterial.reflectionTexture) {
  25664. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25665. }
  25666. skyboxMaterial.disableLighting = true;
  25667. hdrSkybox.infiniteDistance = true;
  25668. hdrSkybox.material = skyboxMaterial;
  25669. }
  25670. return hdrSkybox;
  25671. };
  25672. Scene.prototype.createDefaultEnvironment = function (options) {
  25673. if (BABYLON.EnvironmentHelper) {
  25674. return new BABYLON.EnvironmentHelper(options, this);
  25675. }
  25676. return null;
  25677. };
  25678. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25679. if (webVROptions === void 0) { webVROptions = {}; }
  25680. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25681. };
  25682. // Tags
  25683. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25684. if (tagsQuery === undefined) {
  25685. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25686. return list;
  25687. }
  25688. var listByTags = [];
  25689. forEach = forEach || (function (item) { return; });
  25690. for (var i in list) {
  25691. var item = list[i];
  25692. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25693. listByTags.push(item);
  25694. forEach(item);
  25695. }
  25696. }
  25697. return listByTags;
  25698. };
  25699. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25700. return this._getByTags(this.meshes, tagsQuery, forEach);
  25701. };
  25702. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25703. return this._getByTags(this.cameras, tagsQuery, forEach);
  25704. };
  25705. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25706. return this._getByTags(this.lights, tagsQuery, forEach);
  25707. };
  25708. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25709. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25710. };
  25711. /**
  25712. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25713. * This allowed control for front to back rendering or reversly depending of the special needs.
  25714. *
  25715. * @param renderingGroupId The rendering group id corresponding to its index
  25716. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25717. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25718. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25719. */
  25720. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25721. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25722. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25723. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25724. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25725. };
  25726. /**
  25727. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25728. *
  25729. * @param renderingGroupId The rendering group id corresponding to its index
  25730. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25731. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25732. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25733. */
  25734. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25735. if (depth === void 0) { depth = true; }
  25736. if (stencil === void 0) { stencil = true; }
  25737. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25738. };
  25739. /**
  25740. * Will flag all materials as dirty to trigger new shader compilation
  25741. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25742. */
  25743. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25744. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25745. var material = _a[_i];
  25746. if (predicate && !predicate(material)) {
  25747. continue;
  25748. }
  25749. material.markAsDirty(flag);
  25750. }
  25751. };
  25752. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25753. var _this = this;
  25754. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25755. this._activeRequests.push(request);
  25756. request.onCompleteObservable.add(function (request) {
  25757. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25758. });
  25759. return request;
  25760. };
  25761. /** @ignore */
  25762. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25763. var _this = this;
  25764. return new Promise(function (resolve, reject) {
  25765. _this._loadFile(url, function (data) {
  25766. resolve(data);
  25767. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25768. reject(exception);
  25769. });
  25770. });
  25771. };
  25772. // Statics
  25773. Scene._FOGMODE_NONE = 0;
  25774. Scene._FOGMODE_EXP = 1;
  25775. Scene._FOGMODE_EXP2 = 2;
  25776. Scene._FOGMODE_LINEAR = 3;
  25777. Scene._uniqueIdCounter = 0;
  25778. Scene.MinDeltaTime = 1.0;
  25779. Scene.MaxDeltaTime = 1000.0;
  25780. /** The distance in pixel that you have to move to prevent some events */
  25781. Scene.DragMovementThreshold = 10; // in pixels
  25782. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25783. Scene.LongPressDelay = 500; // in milliseconds
  25784. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25785. Scene.DoubleClickDelay = 300; // in milliseconds
  25786. /** If you need to check double click without raising a single click at first click, enable this flag */
  25787. Scene.ExclusiveDoubleClickMode = false;
  25788. return Scene;
  25789. }());
  25790. BABYLON.Scene = Scene;
  25791. })(BABYLON || (BABYLON = {}));
  25792. //# sourceMappingURL=babylon.scene.js.map
  25793. var BABYLON;
  25794. (function (BABYLON) {
  25795. /**
  25796. * Set of assets to keep when moving a scene into an asset container.
  25797. */
  25798. var KeepAssets = /** @class */ (function () {
  25799. function KeepAssets() {
  25800. /**
  25801. * Cameras to keep.
  25802. */
  25803. this.cameras = new Array();
  25804. /**
  25805. * Lights to keep.
  25806. */
  25807. this.lights = new Array();
  25808. /**
  25809. * Meshes to keep.
  25810. */
  25811. this.meshes = new Array();
  25812. /**
  25813. * Skeletons to keep.
  25814. */
  25815. this.skeletons = new Array();
  25816. /**
  25817. * ParticleSystems to keep.
  25818. */
  25819. this.particleSystems = new Array();
  25820. /**
  25821. * Animations to keep.
  25822. */
  25823. this.animations = new Array();
  25824. /**
  25825. * MultiMaterials to keep.
  25826. */
  25827. this.multiMaterials = new Array();
  25828. /**
  25829. * Materials to keep.
  25830. */
  25831. this.materials = new Array();
  25832. /**
  25833. * MorphTargetManagers to keep.
  25834. */
  25835. this.morphTargetManagers = new Array();
  25836. /**
  25837. * Geometries to keep.
  25838. */
  25839. this.geometries = new Array();
  25840. /**
  25841. * TransformNodes to keep.
  25842. */
  25843. this.transformNodes = new Array();
  25844. /**
  25845. * LensFlareSystems to keep.
  25846. */
  25847. this.lensFlareSystems = new Array();
  25848. /**
  25849. * ShadowGenerators to keep.
  25850. */
  25851. this.shadowGenerators = new Array();
  25852. /**
  25853. * ActionManagers to keep.
  25854. */
  25855. this.actionManagers = new Array();
  25856. /**
  25857. * Sounds to keep.
  25858. */
  25859. this.sounds = new Array();
  25860. }
  25861. return KeepAssets;
  25862. }());
  25863. BABYLON.KeepAssets = KeepAssets;
  25864. /**
  25865. * Container with a set of assets that can be added or removed from a scene.
  25866. */
  25867. var AssetContainer = /** @class */ (function () {
  25868. /**
  25869. * Instantiates an AssetContainer.
  25870. * @param scene The scene the AssetContainer belongs to.
  25871. */
  25872. function AssetContainer(scene) {
  25873. // Objects
  25874. /**
  25875. * Cameras populated in the container.
  25876. */
  25877. this.cameras = new Array();
  25878. /**
  25879. * Lights populated in the container.
  25880. */
  25881. this.lights = new Array();
  25882. /**
  25883. * Meshes populated in the container.
  25884. */
  25885. this.meshes = new Array();
  25886. /**
  25887. * Skeletons populated in the container.
  25888. */
  25889. this.skeletons = new Array();
  25890. /**
  25891. * ParticleSystems populated in the container.
  25892. */
  25893. this.particleSystems = new Array();
  25894. /**
  25895. * Animations populated in the container.
  25896. */
  25897. this.animations = new Array();
  25898. /**
  25899. * MultiMaterials populated in the container.
  25900. */
  25901. this.multiMaterials = new Array();
  25902. /**
  25903. * Materials populated in the container.
  25904. */
  25905. this.materials = new Array();
  25906. /**
  25907. * MorphTargetManagers populated in the container.
  25908. */
  25909. this.morphTargetManagers = new Array();
  25910. /**
  25911. * Geometries populated in the container.
  25912. */
  25913. this.geometries = new Array();
  25914. /**
  25915. * TransformNodes populated in the container.
  25916. */
  25917. this.transformNodes = new Array();
  25918. /**
  25919. * LensFlareSystems populated in the container.
  25920. */
  25921. this.lensFlareSystems = new Array();
  25922. /**
  25923. * ShadowGenerators populated in the container.
  25924. */
  25925. this.shadowGenerators = new Array();
  25926. /**
  25927. * ActionManagers populated in the container.
  25928. */
  25929. this.actionManagers = new Array();
  25930. /**
  25931. * Sounds populated in the container.
  25932. */
  25933. this.sounds = new Array();
  25934. this.scene = scene;
  25935. }
  25936. /**
  25937. * Adds all the assets from the container to the scene.
  25938. */
  25939. AssetContainer.prototype.addAllToScene = function () {
  25940. var _this = this;
  25941. this.cameras.forEach(function (o) {
  25942. _this.scene.addCamera(o);
  25943. });
  25944. this.lights.forEach(function (o) {
  25945. _this.scene.addLight(o);
  25946. });
  25947. this.meshes.forEach(function (o) {
  25948. _this.scene.addMesh(o);
  25949. });
  25950. this.skeletons.forEach(function (o) {
  25951. _this.scene.addSkeleton(o);
  25952. });
  25953. this.particleSystems.forEach(function (o) {
  25954. _this.scene.addParticleSystem(o);
  25955. });
  25956. this.animations.forEach(function (o) {
  25957. _this.scene.addAnimation(o);
  25958. });
  25959. this.multiMaterials.forEach(function (o) {
  25960. _this.scene.addMultiMaterial(o);
  25961. });
  25962. this.materials.forEach(function (o) {
  25963. _this.scene.addMaterial(o);
  25964. });
  25965. this.morphTargetManagers.forEach(function (o) {
  25966. _this.scene.addMorphTargetManager(o);
  25967. });
  25968. this.geometries.forEach(function (o) {
  25969. _this.scene.addGeometry(o);
  25970. });
  25971. this.transformNodes.forEach(function (o) {
  25972. _this.scene.addTransformNode(o);
  25973. });
  25974. this.lensFlareSystems.forEach(function (o) {
  25975. _this.scene.addLensFlareSystem(o);
  25976. });
  25977. this.actionManagers.forEach(function (o) {
  25978. _this.scene.addActionManager(o);
  25979. });
  25980. this.sounds.forEach(function (o) {
  25981. o.play();
  25982. o.autoplay = true;
  25983. _this.scene.mainSoundTrack.AddSound(o);
  25984. });
  25985. };
  25986. /**
  25987. * Removes all the assets in the container from the scene
  25988. */
  25989. AssetContainer.prototype.removeAllFromScene = function () {
  25990. var _this = this;
  25991. this.cameras.forEach(function (o) {
  25992. _this.scene.removeCamera(o);
  25993. });
  25994. this.lights.forEach(function (o) {
  25995. _this.scene.removeLight(o);
  25996. });
  25997. this.meshes.forEach(function (o) {
  25998. _this.scene.removeMesh(o);
  25999. });
  26000. this.skeletons.forEach(function (o) {
  26001. _this.scene.removeSkeleton(o);
  26002. });
  26003. this.particleSystems.forEach(function (o) {
  26004. _this.scene.removeParticleSystem(o);
  26005. });
  26006. this.animations.forEach(function (o) {
  26007. _this.scene.removeAnimation(o);
  26008. });
  26009. this.multiMaterials.forEach(function (o) {
  26010. _this.scene.removeMultiMaterial(o);
  26011. });
  26012. this.materials.forEach(function (o) {
  26013. _this.scene.removeMaterial(o);
  26014. });
  26015. this.morphTargetManagers.forEach(function (o) {
  26016. _this.scene.removeMorphTargetManager(o);
  26017. });
  26018. this.geometries.forEach(function (o) {
  26019. _this.scene.removeGeometry(o);
  26020. });
  26021. this.transformNodes.forEach(function (o) {
  26022. _this.scene.removeTransformNode(o);
  26023. });
  26024. this.lensFlareSystems.forEach(function (o) {
  26025. _this.scene.removeLensFlareSystem(o);
  26026. });
  26027. this.actionManagers.forEach(function (o) {
  26028. _this.scene.removeActionManager(o);
  26029. });
  26030. this.sounds.forEach(function (o) {
  26031. o.stop();
  26032. o.autoplay = false;
  26033. _this.scene.mainSoundTrack.RemoveSound(o);
  26034. });
  26035. };
  26036. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  26037. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  26038. var asset = sourceAssets_1[_i];
  26039. var move = true;
  26040. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  26041. var keepAsset = keepAssets_1[_a];
  26042. if (asset === keepAsset) {
  26043. move = false;
  26044. break;
  26045. }
  26046. }
  26047. if (move) {
  26048. targetAssets.push(asset);
  26049. }
  26050. }
  26051. };
  26052. /**
  26053. * Removes all the assets contained in the scene and adds them to the container.
  26054. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  26055. */
  26056. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  26057. if (keepAssets === undefined) {
  26058. keepAssets = new KeepAssets();
  26059. }
  26060. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  26061. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  26062. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  26063. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  26064. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  26065. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  26066. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  26067. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  26068. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  26069. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  26070. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  26071. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  26072. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  26073. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  26074. this.removeAllFromScene();
  26075. };
  26076. return AssetContainer;
  26077. }());
  26078. BABYLON.AssetContainer = AssetContainer;
  26079. })(BABYLON || (BABYLON = {}));
  26080. //# sourceMappingURL=babylon.assetContainer.js.map
  26081. var BABYLON;
  26082. (function (BABYLON) {
  26083. var Buffer = /** @class */ (function () {
  26084. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  26085. if (instanced === void 0) { instanced = false; }
  26086. if (engine instanceof BABYLON.Mesh) {
  26087. this._engine = engine.getScene().getEngine();
  26088. }
  26089. else {
  26090. this._engine = engine;
  26091. }
  26092. this._updatable = updatable;
  26093. this._instanced = instanced;
  26094. this._data = data;
  26095. this._strideSize = stride;
  26096. if (!postponeInternalCreation) {
  26097. this.create();
  26098. }
  26099. }
  26100. /**
  26101. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  26102. * @param kind defines the vertex buffer kind (position, normal, etc.)
  26103. * @param offset defines offset in the buffer (0 by default)
  26104. * @param size defines the size in floats of attributes (position is 3 for instance)
  26105. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  26106. * @param instanced defines if the vertex buffer contains indexed data
  26107. * @returns the new vertex buffer
  26108. */
  26109. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  26110. // a lot of these parameters are ignored as they are overriden by the buffer
  26111. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  26112. };
  26113. // Properties
  26114. Buffer.prototype.isUpdatable = function () {
  26115. return this._updatable;
  26116. };
  26117. Buffer.prototype.getData = function () {
  26118. return this._data;
  26119. };
  26120. Buffer.prototype.getBuffer = function () {
  26121. return this._buffer;
  26122. };
  26123. Buffer.prototype.getStrideSize = function () {
  26124. return this._strideSize;
  26125. };
  26126. // public getIsInstanced(): boolean {
  26127. // return this._instanced;
  26128. // }
  26129. // public get instanceDivisor(): number {
  26130. // return this._instanceDivisor;
  26131. // }
  26132. // public set instanceDivisor(value: number) {
  26133. // this._instanceDivisor = value;
  26134. // if (value == 0) {
  26135. // this._instanced = false;
  26136. // } else {
  26137. // this._instanced = true;
  26138. // }
  26139. // }
  26140. // Methods
  26141. Buffer.prototype.create = function (data) {
  26142. if (data === void 0) { data = null; }
  26143. if (!data && this._buffer) {
  26144. return; // nothing to do
  26145. }
  26146. data = data || this._data;
  26147. if (!data) {
  26148. return;
  26149. }
  26150. if (!this._buffer) {
  26151. if (this._updatable) {
  26152. this._buffer = this._engine.createDynamicVertexBuffer(data);
  26153. this._data = data;
  26154. }
  26155. else {
  26156. this._buffer = this._engine.createVertexBuffer(data);
  26157. }
  26158. }
  26159. else if (this._updatable) {
  26160. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  26161. this._data = data;
  26162. }
  26163. };
  26164. Buffer.prototype._rebuild = function () {
  26165. this._buffer = null;
  26166. this.create(this._data);
  26167. };
  26168. Buffer.prototype.update = function (data) {
  26169. this.create(data);
  26170. };
  26171. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  26172. if (!this._buffer) {
  26173. return;
  26174. }
  26175. if (this._updatable) {
  26176. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  26177. this._data = null;
  26178. }
  26179. };
  26180. Buffer.prototype.dispose = function () {
  26181. if (!this._buffer) {
  26182. return;
  26183. }
  26184. if (this._engine._releaseBuffer(this._buffer)) {
  26185. this._buffer = null;
  26186. }
  26187. };
  26188. return Buffer;
  26189. }());
  26190. BABYLON.Buffer = Buffer;
  26191. })(BABYLON || (BABYLON = {}));
  26192. //# sourceMappingURL=babylon.buffer.js.map
  26193. var BABYLON;
  26194. (function (BABYLON) {
  26195. var VertexBuffer = /** @class */ (function () {
  26196. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  26197. if (data instanceof BABYLON.Buffer) {
  26198. if (!stride) {
  26199. stride = data.getStrideSize();
  26200. }
  26201. this._buffer = data;
  26202. this._ownsBuffer = false;
  26203. }
  26204. else {
  26205. if (!stride) {
  26206. stride = VertexBuffer.DeduceStride(kind);
  26207. }
  26208. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  26209. this._ownsBuffer = true;
  26210. }
  26211. this._stride = stride;
  26212. this._instanced = instanced !== undefined ? instanced : false;
  26213. this._instanceDivisor = instanced ? 1 : 0;
  26214. this._offset = offset ? offset : 0;
  26215. this._size = size ? size : stride;
  26216. this._kind = kind;
  26217. }
  26218. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  26219. /**
  26220. * Gets or sets the instance divisor when in instanced mode
  26221. */
  26222. get: function () {
  26223. return this._instanceDivisor;
  26224. },
  26225. set: function (value) {
  26226. this._instanceDivisor = value;
  26227. if (value == 0) {
  26228. this._instanced = false;
  26229. }
  26230. else {
  26231. this._instanced = true;
  26232. }
  26233. },
  26234. enumerable: true,
  26235. configurable: true
  26236. });
  26237. VertexBuffer.prototype._rebuild = function () {
  26238. if (!this._buffer) {
  26239. return;
  26240. }
  26241. this._buffer._rebuild();
  26242. };
  26243. /**
  26244. * Returns the kind of the VertexBuffer (string).
  26245. */
  26246. VertexBuffer.prototype.getKind = function () {
  26247. return this._kind;
  26248. };
  26249. // Properties
  26250. /**
  26251. * Boolean : is the VertexBuffer updatable ?
  26252. */
  26253. VertexBuffer.prototype.isUpdatable = function () {
  26254. return this._buffer.isUpdatable();
  26255. };
  26256. /**
  26257. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  26258. */
  26259. VertexBuffer.prototype.getData = function () {
  26260. return this._buffer.getData();
  26261. };
  26262. /**
  26263. * Returns the WebGLBuffer associated to the VertexBuffer.
  26264. */
  26265. VertexBuffer.prototype.getBuffer = function () {
  26266. return this._buffer.getBuffer();
  26267. };
  26268. /**
  26269. * Returns the stride of the VertexBuffer (integer).
  26270. */
  26271. VertexBuffer.prototype.getStrideSize = function () {
  26272. return this._stride;
  26273. };
  26274. /**
  26275. * Returns the offset (integer).
  26276. */
  26277. VertexBuffer.prototype.getOffset = function () {
  26278. return this._offset;
  26279. };
  26280. /**
  26281. * Returns the VertexBuffer total size (integer).
  26282. */
  26283. VertexBuffer.prototype.getSize = function () {
  26284. return this._size;
  26285. };
  26286. /**
  26287. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  26288. */
  26289. VertexBuffer.prototype.getIsInstanced = function () {
  26290. return this._instanced;
  26291. };
  26292. /**
  26293. * Returns the instancing divisor, zero for non-instanced (integer).
  26294. */
  26295. VertexBuffer.prototype.getInstanceDivisor = function () {
  26296. return this._instanceDivisor;
  26297. };
  26298. // Methods
  26299. /**
  26300. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  26301. * Returns the created WebGLBuffer.
  26302. */
  26303. VertexBuffer.prototype.create = function (data) {
  26304. return this._buffer.create(data);
  26305. };
  26306. /**
  26307. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26308. * This function will create a new buffer if the current one is not updatable
  26309. * Returns the updated WebGLBuffer.
  26310. */
  26311. VertexBuffer.prototype.update = function (data) {
  26312. return this._buffer.update(data);
  26313. };
  26314. /**
  26315. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26316. * Returns the directly updated WebGLBuffer.
  26317. */
  26318. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  26319. return this._buffer.updateDirectly(data, offset);
  26320. };
  26321. /**
  26322. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  26323. */
  26324. VertexBuffer.prototype.dispose = function () {
  26325. if (this._ownsBuffer) {
  26326. this._buffer.dispose();
  26327. }
  26328. };
  26329. Object.defineProperty(VertexBuffer, "PositionKind", {
  26330. get: function () {
  26331. return VertexBuffer._PositionKind;
  26332. },
  26333. enumerable: true,
  26334. configurable: true
  26335. });
  26336. Object.defineProperty(VertexBuffer, "NormalKind", {
  26337. get: function () {
  26338. return VertexBuffer._NormalKind;
  26339. },
  26340. enumerable: true,
  26341. configurable: true
  26342. });
  26343. Object.defineProperty(VertexBuffer, "TangentKind", {
  26344. get: function () {
  26345. return VertexBuffer._TangentKind;
  26346. },
  26347. enumerable: true,
  26348. configurable: true
  26349. });
  26350. Object.defineProperty(VertexBuffer, "UVKind", {
  26351. get: function () {
  26352. return VertexBuffer._UVKind;
  26353. },
  26354. enumerable: true,
  26355. configurable: true
  26356. });
  26357. Object.defineProperty(VertexBuffer, "UV2Kind", {
  26358. get: function () {
  26359. return VertexBuffer._UV2Kind;
  26360. },
  26361. enumerable: true,
  26362. configurable: true
  26363. });
  26364. Object.defineProperty(VertexBuffer, "UV3Kind", {
  26365. get: function () {
  26366. return VertexBuffer._UV3Kind;
  26367. },
  26368. enumerable: true,
  26369. configurable: true
  26370. });
  26371. Object.defineProperty(VertexBuffer, "UV4Kind", {
  26372. get: function () {
  26373. return VertexBuffer._UV4Kind;
  26374. },
  26375. enumerable: true,
  26376. configurable: true
  26377. });
  26378. Object.defineProperty(VertexBuffer, "UV5Kind", {
  26379. get: function () {
  26380. return VertexBuffer._UV5Kind;
  26381. },
  26382. enumerable: true,
  26383. configurable: true
  26384. });
  26385. Object.defineProperty(VertexBuffer, "UV6Kind", {
  26386. get: function () {
  26387. return VertexBuffer._UV6Kind;
  26388. },
  26389. enumerable: true,
  26390. configurable: true
  26391. });
  26392. Object.defineProperty(VertexBuffer, "ColorKind", {
  26393. get: function () {
  26394. return VertexBuffer._ColorKind;
  26395. },
  26396. enumerable: true,
  26397. configurable: true
  26398. });
  26399. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  26400. get: function () {
  26401. return VertexBuffer._MatricesIndicesKind;
  26402. },
  26403. enumerable: true,
  26404. configurable: true
  26405. });
  26406. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  26407. get: function () {
  26408. return VertexBuffer._MatricesWeightsKind;
  26409. },
  26410. enumerable: true,
  26411. configurable: true
  26412. });
  26413. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  26414. get: function () {
  26415. return VertexBuffer._MatricesIndicesExtraKind;
  26416. },
  26417. enumerable: true,
  26418. configurable: true
  26419. });
  26420. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  26421. get: function () {
  26422. return VertexBuffer._MatricesWeightsExtraKind;
  26423. },
  26424. enumerable: true,
  26425. configurable: true
  26426. });
  26427. /**
  26428. * Deduces the stride given a kind.
  26429. * @param kind The kind string to deduce
  26430. * @returns The deduced stride
  26431. */
  26432. VertexBuffer.DeduceStride = function (kind) {
  26433. switch (kind) {
  26434. case VertexBuffer.UVKind:
  26435. case VertexBuffer.UV2Kind:
  26436. case VertexBuffer.UV3Kind:
  26437. case VertexBuffer.UV4Kind:
  26438. case VertexBuffer.UV5Kind:
  26439. case VertexBuffer.UV6Kind:
  26440. return 2;
  26441. case VertexBuffer.NormalKind:
  26442. case VertexBuffer.PositionKind:
  26443. return 3;
  26444. case VertexBuffer.ColorKind:
  26445. case VertexBuffer.MatricesIndicesKind:
  26446. case VertexBuffer.MatricesIndicesExtraKind:
  26447. case VertexBuffer.MatricesWeightsKind:
  26448. case VertexBuffer.MatricesWeightsExtraKind:
  26449. case VertexBuffer.TangentKind:
  26450. return 4;
  26451. default:
  26452. throw new Error("Invalid kind '" + kind + "'");
  26453. }
  26454. };
  26455. // Enums
  26456. VertexBuffer._PositionKind = "position";
  26457. VertexBuffer._NormalKind = "normal";
  26458. VertexBuffer._TangentKind = "tangent";
  26459. VertexBuffer._UVKind = "uv";
  26460. VertexBuffer._UV2Kind = "uv2";
  26461. VertexBuffer._UV3Kind = "uv3";
  26462. VertexBuffer._UV4Kind = "uv4";
  26463. VertexBuffer._UV5Kind = "uv5";
  26464. VertexBuffer._UV6Kind = "uv6";
  26465. VertexBuffer._ColorKind = "color";
  26466. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  26467. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  26468. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  26469. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  26470. return VertexBuffer;
  26471. }());
  26472. BABYLON.VertexBuffer = VertexBuffer;
  26473. })(BABYLON || (BABYLON = {}));
  26474. //# sourceMappingURL=babylon.vertexBuffer.js.map
  26475. var BABYLON;
  26476. (function (BABYLON) {
  26477. /**
  26478. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  26479. */
  26480. var DummyInternalTextureTracker = /** @class */ (function () {
  26481. function DummyInternalTextureTracker() {
  26482. /**
  26483. * Gets or set the previous tracker in the list
  26484. */
  26485. this.previous = null;
  26486. /**
  26487. * Gets or set the next tracker in the list
  26488. */
  26489. this.next = null;
  26490. }
  26491. return DummyInternalTextureTracker;
  26492. }());
  26493. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  26494. })(BABYLON || (BABYLON = {}));
  26495. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26496. var BABYLON;
  26497. (function (BABYLON) {
  26498. /**
  26499. * Class used to store data associated with WebGL texture data for the engine
  26500. * This class should not be used directly
  26501. */
  26502. var InternalTexture = /** @class */ (function () {
  26503. /**
  26504. * Creates a new InternalTexture
  26505. * @param engine defines the engine to use
  26506. * @param dataSource defines the type of data that will be used
  26507. */
  26508. function InternalTexture(engine, dataSource) {
  26509. /**
  26510. * Observable called when the texture is loaded
  26511. */
  26512. this.onLoadedObservable = new BABYLON.Observable();
  26513. /**
  26514. * Gets or set the previous tracker in the list
  26515. */
  26516. this.previous = null;
  26517. /**
  26518. * Gets or set the next tracker in the list
  26519. */
  26520. this.next = null;
  26521. // Private
  26522. /** @ignore */
  26523. this._initialSlot = -1;
  26524. /** @ignore */
  26525. this._designatedSlot = -1;
  26526. /** @ignore */
  26527. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26528. /** @ignore */
  26529. this._comparisonFunction = 0;
  26530. /** @ignore */
  26531. this._references = 1;
  26532. this._engine = engine;
  26533. this._dataSource = dataSource;
  26534. this._webGLTexture = engine._createTexture();
  26535. }
  26536. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26537. /**
  26538. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26539. */
  26540. get: function () {
  26541. return this._dataSource;
  26542. },
  26543. enumerable: true,
  26544. configurable: true
  26545. });
  26546. /**
  26547. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26548. */
  26549. InternalTexture.prototype.incrementReferences = function () {
  26550. this._references++;
  26551. };
  26552. /**
  26553. * Change the size of the texture (not the size of the content)
  26554. * @param width defines the new width
  26555. * @param height defines the new height
  26556. * @param depth defines the new depth (1 by default)
  26557. */
  26558. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26559. if (depth === void 0) { depth = 1; }
  26560. this.width = width;
  26561. this.height = height;
  26562. this.depth = depth;
  26563. this.baseWidth = width;
  26564. this.baseHeight = height;
  26565. this.baseDepth = depth;
  26566. this._size = width * height * depth;
  26567. };
  26568. /** @ignore */
  26569. InternalTexture.prototype._rebuild = function () {
  26570. var _this = this;
  26571. var proxy;
  26572. this.isReady = false;
  26573. this._cachedCoordinatesMode = null;
  26574. this._cachedWrapU = null;
  26575. this._cachedWrapV = null;
  26576. this._cachedAnisotropicFilteringLevel = null;
  26577. switch (this._dataSource) {
  26578. case InternalTexture.DATASOURCE_TEMP:
  26579. return;
  26580. case InternalTexture.DATASOURCE_URL:
  26581. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26582. _this.isReady = true;
  26583. }, null, this._buffer, undefined, this.format);
  26584. proxy._swapAndDie(this);
  26585. return;
  26586. case InternalTexture.DATASOURCE_RAW:
  26587. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26588. proxy._swapAndDie(this);
  26589. this.isReady = true;
  26590. return;
  26591. case InternalTexture.DATASOURCE_RAW3D:
  26592. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26593. proxy._swapAndDie(this);
  26594. this.isReady = true;
  26595. return;
  26596. case InternalTexture.DATASOURCE_DYNAMIC:
  26597. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26598. proxy._swapAndDie(this);
  26599. // The engine will make sure to update content so no need to flag it as isReady = true
  26600. return;
  26601. case InternalTexture.DATASOURCE_RENDERTARGET:
  26602. var options = new BABYLON.RenderTargetCreationOptions();
  26603. options.generateDepthBuffer = this._generateDepthBuffer;
  26604. options.generateMipMaps = this.generateMipMaps;
  26605. options.generateStencilBuffer = this._generateStencilBuffer;
  26606. options.samplingMode = this.samplingMode;
  26607. options.type = this.type;
  26608. if (this.isCube) {
  26609. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26610. }
  26611. else {
  26612. var size = {
  26613. width: this.width,
  26614. height: this.height
  26615. };
  26616. proxy = this._engine.createRenderTargetTexture(size, options);
  26617. }
  26618. proxy._swapAndDie(this);
  26619. this.isReady = true;
  26620. return;
  26621. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26622. var depthTextureOptions = {
  26623. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26624. comparisonFunction: this._comparisonFunction,
  26625. generateStencil: this._generateStencilBuffer,
  26626. isCube: this.isCube
  26627. };
  26628. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26629. proxy._swapAndDie(this);
  26630. this.isReady = true;
  26631. return;
  26632. case InternalTexture.DATASOURCE_CUBE:
  26633. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26634. _this.isReady = true;
  26635. }, null, this.format, this._extension);
  26636. proxy._swapAndDie(this);
  26637. return;
  26638. case InternalTexture.DATASOURCE_CUBERAW:
  26639. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26640. proxy._swapAndDie(this);
  26641. this.isReady = true;
  26642. return;
  26643. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26644. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26645. if (proxy) {
  26646. proxy._swapAndDie(_this);
  26647. }
  26648. _this.isReady = true;
  26649. }, null, this.format, this._extension);
  26650. return;
  26651. }
  26652. };
  26653. InternalTexture.prototype._swapAndDie = function (target) {
  26654. target._webGLTexture = this._webGLTexture;
  26655. if (this._framebuffer) {
  26656. target._framebuffer = this._framebuffer;
  26657. }
  26658. if (this._depthStencilBuffer) {
  26659. target._depthStencilBuffer = this._depthStencilBuffer;
  26660. }
  26661. if (this._lodTextureHigh) {
  26662. if (target._lodTextureHigh) {
  26663. target._lodTextureHigh.dispose();
  26664. }
  26665. target._lodTextureHigh = this._lodTextureHigh;
  26666. }
  26667. if (this._lodTextureMid) {
  26668. if (target._lodTextureMid) {
  26669. target._lodTextureMid.dispose();
  26670. }
  26671. target._lodTextureMid = this._lodTextureMid;
  26672. }
  26673. if (this._lodTextureLow) {
  26674. if (target._lodTextureLow) {
  26675. target._lodTextureLow.dispose();
  26676. }
  26677. target._lodTextureLow = this._lodTextureLow;
  26678. }
  26679. var cache = this._engine.getLoadedTexturesCache();
  26680. var index = cache.indexOf(this);
  26681. if (index !== -1) {
  26682. cache.splice(index, 1);
  26683. }
  26684. };
  26685. /**
  26686. * Dispose the current allocated resources
  26687. */
  26688. InternalTexture.prototype.dispose = function () {
  26689. if (!this._webGLTexture) {
  26690. return;
  26691. }
  26692. this._references--;
  26693. if (this._references === 0) {
  26694. this._engine._releaseTexture(this);
  26695. this._webGLTexture = null;
  26696. this.previous = null;
  26697. this.next = null;
  26698. }
  26699. };
  26700. /**
  26701. * The source of the texture data is unknown
  26702. */
  26703. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26704. /**
  26705. * Texture data comes from an URL
  26706. */
  26707. InternalTexture.DATASOURCE_URL = 1;
  26708. /**
  26709. * Texture data is only used for temporary storage
  26710. */
  26711. InternalTexture.DATASOURCE_TEMP = 2;
  26712. /**
  26713. * Texture data comes from raw data (ArrayBuffer)
  26714. */
  26715. InternalTexture.DATASOURCE_RAW = 3;
  26716. /**
  26717. * Texture content is dynamic (video or dynamic texture)
  26718. */
  26719. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26720. /**
  26721. * Texture content is generated by rendering to it
  26722. */
  26723. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26724. /**
  26725. * Texture content is part of a multi render target process
  26726. */
  26727. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26728. /**
  26729. * Texture data comes from a cube data file
  26730. */
  26731. InternalTexture.DATASOURCE_CUBE = 7;
  26732. /**
  26733. * Texture data comes from a raw cube data
  26734. */
  26735. InternalTexture.DATASOURCE_CUBERAW = 8;
  26736. /**
  26737. * Texture data come from a prefiltered cube data file
  26738. */
  26739. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26740. /**
  26741. * Texture content is raw 3D data
  26742. */
  26743. InternalTexture.DATASOURCE_RAW3D = 10;
  26744. /**
  26745. * Texture content is a depth texture
  26746. */
  26747. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26748. return InternalTexture;
  26749. }());
  26750. BABYLON.InternalTexture = InternalTexture;
  26751. })(BABYLON || (BABYLON = {}));
  26752. //# sourceMappingURL=babylon.internalTexture.js.map
  26753. var BABYLON;
  26754. (function (BABYLON) {
  26755. var BaseTexture = /** @class */ (function () {
  26756. function BaseTexture(scene) {
  26757. this._hasAlpha = false;
  26758. this.getAlphaFromRGB = false;
  26759. this.level = 1;
  26760. this.coordinatesIndex = 0;
  26761. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26762. /**
  26763. * | Value | Type | Description |
  26764. * | ----- | ------------------ | ----------- |
  26765. * | 0 | CLAMP_ADDRESSMODE | |
  26766. * | 1 | WRAP_ADDRESSMODE | |
  26767. * | 2 | MIRROR_ADDRESSMODE | |
  26768. */
  26769. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26770. /**
  26771. * | Value | Type | Description |
  26772. * | ----- | ------------------ | ----------- |
  26773. * | 0 | CLAMP_ADDRESSMODE | |
  26774. * | 1 | WRAP_ADDRESSMODE | |
  26775. * | 2 | MIRROR_ADDRESSMODE | |
  26776. */
  26777. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26778. /**
  26779. * | Value | Type | Description |
  26780. * | ----- | ------------------ | ----------- |
  26781. * | 0 | CLAMP_ADDRESSMODE | |
  26782. * | 1 | WRAP_ADDRESSMODE | |
  26783. * | 2 | MIRROR_ADDRESSMODE | |
  26784. */
  26785. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26786. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26787. this.isCube = false;
  26788. this.is3D = false;
  26789. this.gammaSpace = true;
  26790. this.invertZ = false;
  26791. this.lodLevelInAlpha = false;
  26792. this.lodGenerationOffset = 0.0;
  26793. this.lodGenerationScale = 0.8;
  26794. this.isRenderTarget = false;
  26795. this.animations = new Array();
  26796. /**
  26797. * An event triggered when the texture is disposed.
  26798. * @type {BABYLON.Observable}
  26799. */
  26800. this.onDisposeObservable = new BABYLON.Observable();
  26801. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26802. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26803. if (this._scene) {
  26804. this._scene.textures.push(this);
  26805. }
  26806. this._uid = null;
  26807. }
  26808. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26809. get: function () {
  26810. return this._hasAlpha;
  26811. },
  26812. set: function (value) {
  26813. if (this._hasAlpha === value) {
  26814. return;
  26815. }
  26816. this._hasAlpha = value;
  26817. if (this._scene) {
  26818. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26819. }
  26820. },
  26821. enumerable: true,
  26822. configurable: true
  26823. });
  26824. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26825. get: function () {
  26826. return this._coordinatesMode;
  26827. },
  26828. /**
  26829. * How a texture is mapped.
  26830. *
  26831. * | Value | Type | Description |
  26832. * | ----- | ----------------------------------- | ----------- |
  26833. * | 0 | EXPLICIT_MODE | |
  26834. * | 1 | SPHERICAL_MODE | |
  26835. * | 2 | PLANAR_MODE | |
  26836. * | 3 | CUBIC_MODE | |
  26837. * | 4 | PROJECTION_MODE | |
  26838. * | 5 | SKYBOX_MODE | |
  26839. * | 6 | INVCUBIC_MODE | |
  26840. * | 7 | EQUIRECTANGULAR_MODE | |
  26841. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26842. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26843. */
  26844. set: function (value) {
  26845. if (this._coordinatesMode === value) {
  26846. return;
  26847. }
  26848. this._coordinatesMode = value;
  26849. if (this._scene) {
  26850. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26851. }
  26852. },
  26853. enumerable: true,
  26854. configurable: true
  26855. });
  26856. Object.defineProperty(BaseTexture.prototype, "uid", {
  26857. get: function () {
  26858. if (!this._uid) {
  26859. this._uid = BABYLON.Tools.RandomId();
  26860. }
  26861. return this._uid;
  26862. },
  26863. enumerable: true,
  26864. configurable: true
  26865. });
  26866. BaseTexture.prototype.toString = function () {
  26867. return this.name;
  26868. };
  26869. BaseTexture.prototype.getClassName = function () {
  26870. return "BaseTexture";
  26871. };
  26872. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26873. set: function (callback) {
  26874. if (this._onDisposeObserver) {
  26875. this.onDisposeObservable.remove(this._onDisposeObserver);
  26876. }
  26877. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26878. },
  26879. enumerable: true,
  26880. configurable: true
  26881. });
  26882. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26883. get: function () {
  26884. return true;
  26885. },
  26886. enumerable: true,
  26887. configurable: true
  26888. });
  26889. BaseTexture.prototype.getScene = function () {
  26890. return this._scene;
  26891. };
  26892. BaseTexture.prototype.getTextureMatrix = function () {
  26893. return BABYLON.Matrix.IdentityReadOnly;
  26894. };
  26895. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26896. return BABYLON.Matrix.IdentityReadOnly;
  26897. };
  26898. BaseTexture.prototype.getInternalTexture = function () {
  26899. return this._texture;
  26900. };
  26901. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  26902. return !this.isBlocking || this.isReady();
  26903. };
  26904. BaseTexture.prototype.isReady = function () {
  26905. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26906. this.delayLoad();
  26907. return false;
  26908. }
  26909. if (this._texture) {
  26910. return this._texture.isReady;
  26911. }
  26912. return false;
  26913. };
  26914. BaseTexture.prototype.getSize = function () {
  26915. if (this._texture && this._texture.width) {
  26916. return new BABYLON.Size(this._texture.width, this._texture.height);
  26917. }
  26918. if (this._texture && this._texture._size) {
  26919. return new BABYLON.Size(this._texture._size, this._texture._size);
  26920. }
  26921. return BABYLON.Size.Zero();
  26922. };
  26923. BaseTexture.prototype.getBaseSize = function () {
  26924. if (!this.isReady() || !this._texture)
  26925. return BABYLON.Size.Zero();
  26926. if (this._texture._size) {
  26927. return new BABYLON.Size(this._texture._size, this._texture._size);
  26928. }
  26929. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  26930. };
  26931. BaseTexture.prototype.scale = function (ratio) {
  26932. };
  26933. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26934. get: function () {
  26935. return false;
  26936. },
  26937. enumerable: true,
  26938. configurable: true
  26939. });
  26940. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  26941. if (!this._scene) {
  26942. return null;
  26943. }
  26944. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26945. for (var index = 0; index < texturesCache.length; index++) {
  26946. var texturesCacheEntry = texturesCache[index];
  26947. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  26948. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  26949. texturesCacheEntry.incrementReferences();
  26950. return texturesCacheEntry;
  26951. }
  26952. }
  26953. }
  26954. return null;
  26955. };
  26956. BaseTexture.prototype._rebuild = function () {
  26957. };
  26958. BaseTexture.prototype.delayLoad = function () {
  26959. };
  26960. BaseTexture.prototype.clone = function () {
  26961. return null;
  26962. };
  26963. Object.defineProperty(BaseTexture.prototype, "textureType", {
  26964. get: function () {
  26965. if (!this._texture) {
  26966. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26967. }
  26968. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26969. },
  26970. enumerable: true,
  26971. configurable: true
  26972. });
  26973. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  26974. get: function () {
  26975. if (!this._texture) {
  26976. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26977. }
  26978. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26979. },
  26980. enumerable: true,
  26981. configurable: true
  26982. });
  26983. BaseTexture.prototype.readPixels = function (faceIndex) {
  26984. if (faceIndex === void 0) { faceIndex = 0; }
  26985. if (!this._texture) {
  26986. return null;
  26987. }
  26988. var size = this.getSize();
  26989. var scene = this.getScene();
  26990. if (!scene) {
  26991. return null;
  26992. }
  26993. var engine = scene.getEngine();
  26994. if (this._texture.isCube) {
  26995. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  26996. }
  26997. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  26998. };
  26999. BaseTexture.prototype.releaseInternalTexture = function () {
  27000. if (this._texture) {
  27001. this._texture.dispose();
  27002. this._texture = null;
  27003. }
  27004. };
  27005. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  27006. get: function () {
  27007. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  27008. return null;
  27009. }
  27010. if (!this._texture._sphericalPolynomial) {
  27011. this._texture._sphericalPolynomial =
  27012. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  27013. }
  27014. return this._texture._sphericalPolynomial;
  27015. },
  27016. set: function (value) {
  27017. if (this._texture) {
  27018. this._texture._sphericalPolynomial = value;
  27019. }
  27020. },
  27021. enumerable: true,
  27022. configurable: true
  27023. });
  27024. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  27025. get: function () {
  27026. if (this._texture) {
  27027. return this._texture._lodTextureHigh;
  27028. }
  27029. return null;
  27030. },
  27031. enumerable: true,
  27032. configurable: true
  27033. });
  27034. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  27035. get: function () {
  27036. if (this._texture) {
  27037. return this._texture._lodTextureMid;
  27038. }
  27039. return null;
  27040. },
  27041. enumerable: true,
  27042. configurable: true
  27043. });
  27044. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  27045. get: function () {
  27046. if (this._texture) {
  27047. return this._texture._lodTextureLow;
  27048. }
  27049. return null;
  27050. },
  27051. enumerable: true,
  27052. configurable: true
  27053. });
  27054. BaseTexture.prototype.dispose = function () {
  27055. if (!this._scene) {
  27056. return;
  27057. }
  27058. // Animations
  27059. this._scene.stopAnimation(this);
  27060. // Remove from scene
  27061. this._scene._removePendingData(this);
  27062. var index = this._scene.textures.indexOf(this);
  27063. if (index >= 0) {
  27064. this._scene.textures.splice(index, 1);
  27065. }
  27066. if (this._texture === undefined) {
  27067. return;
  27068. }
  27069. // Release
  27070. this.releaseInternalTexture();
  27071. // Callback
  27072. this.onDisposeObservable.notifyObservers(this);
  27073. this.onDisposeObservable.clear();
  27074. };
  27075. BaseTexture.prototype.serialize = function () {
  27076. if (!this.name) {
  27077. return null;
  27078. }
  27079. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  27080. // Animations
  27081. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27082. return serializationObject;
  27083. };
  27084. BaseTexture.WhenAllReady = function (textures, callback) {
  27085. var numRemaining = textures.length;
  27086. if (numRemaining === 0) {
  27087. callback();
  27088. return;
  27089. }
  27090. var _loop_1 = function () {
  27091. texture = textures[i];
  27092. if (texture.isReady()) {
  27093. if (--numRemaining === 0) {
  27094. callback();
  27095. }
  27096. }
  27097. else {
  27098. onLoadObservable = texture.onLoadObservable;
  27099. var onLoadCallback_1 = function () {
  27100. onLoadObservable.removeCallback(onLoadCallback_1);
  27101. if (--numRemaining === 0) {
  27102. callback();
  27103. }
  27104. };
  27105. onLoadObservable.add(onLoadCallback_1);
  27106. }
  27107. };
  27108. var texture, onLoadObservable;
  27109. for (var i = 0; i < textures.length; i++) {
  27110. _loop_1();
  27111. }
  27112. };
  27113. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  27114. __decorate([
  27115. BABYLON.serialize()
  27116. ], BaseTexture.prototype, "name", void 0);
  27117. __decorate([
  27118. BABYLON.serialize("hasAlpha")
  27119. ], BaseTexture.prototype, "_hasAlpha", void 0);
  27120. __decorate([
  27121. BABYLON.serialize()
  27122. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  27123. __decorate([
  27124. BABYLON.serialize()
  27125. ], BaseTexture.prototype, "level", void 0);
  27126. __decorate([
  27127. BABYLON.serialize()
  27128. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  27129. __decorate([
  27130. BABYLON.serialize("coordinatesMode")
  27131. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  27132. __decorate([
  27133. BABYLON.serialize()
  27134. ], BaseTexture.prototype, "wrapU", void 0);
  27135. __decorate([
  27136. BABYLON.serialize()
  27137. ], BaseTexture.prototype, "wrapV", void 0);
  27138. __decorate([
  27139. BABYLON.serialize()
  27140. ], BaseTexture.prototype, "wrapR", void 0);
  27141. __decorate([
  27142. BABYLON.serialize()
  27143. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  27144. __decorate([
  27145. BABYLON.serialize()
  27146. ], BaseTexture.prototype, "isCube", void 0);
  27147. __decorate([
  27148. BABYLON.serialize()
  27149. ], BaseTexture.prototype, "is3D", void 0);
  27150. __decorate([
  27151. BABYLON.serialize()
  27152. ], BaseTexture.prototype, "gammaSpace", void 0);
  27153. __decorate([
  27154. BABYLON.serialize()
  27155. ], BaseTexture.prototype, "invertZ", void 0);
  27156. __decorate([
  27157. BABYLON.serialize()
  27158. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  27159. __decorate([
  27160. BABYLON.serialize()
  27161. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  27162. __decorate([
  27163. BABYLON.serialize()
  27164. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  27165. __decorate([
  27166. BABYLON.serialize()
  27167. ], BaseTexture.prototype, "isRenderTarget", void 0);
  27168. return BaseTexture;
  27169. }());
  27170. BABYLON.BaseTexture = BaseTexture;
  27171. })(BABYLON || (BABYLON = {}));
  27172. //# sourceMappingURL=babylon.baseTexture.js.map
  27173. var BABYLON;
  27174. (function (BABYLON) {
  27175. var Texture = /** @class */ (function (_super) {
  27176. __extends(Texture, _super);
  27177. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  27178. if (noMipmap === void 0) { noMipmap = false; }
  27179. if (invertY === void 0) { invertY = true; }
  27180. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27181. if (onLoad === void 0) { onLoad = null; }
  27182. if (onError === void 0) { onError = null; }
  27183. if (buffer === void 0) { buffer = null; }
  27184. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27185. var _this = _super.call(this, scene) || this;
  27186. _this.uOffset = 0;
  27187. _this.vOffset = 0;
  27188. _this.uScale = 1.0;
  27189. _this.vScale = 1.0;
  27190. _this.uAng = 0;
  27191. _this.vAng = 0;
  27192. _this.wAng = 0;
  27193. _this._isBlocking = true;
  27194. _this.name = url || "";
  27195. _this.url = url;
  27196. _this._noMipmap = noMipmap;
  27197. _this._invertY = invertY;
  27198. _this._samplingMode = samplingMode;
  27199. _this._buffer = buffer;
  27200. _this._deleteBuffer = deleteBuffer;
  27201. if (format) {
  27202. _this._format = format;
  27203. }
  27204. scene = _this.getScene();
  27205. if (!scene) {
  27206. return _this;
  27207. }
  27208. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  27209. var load = function () {
  27210. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  27211. _this.onLoadObservable.notifyObservers(_this);
  27212. }
  27213. if (onLoad) {
  27214. onLoad();
  27215. }
  27216. if (!_this.isBlocking && scene) {
  27217. scene.resetCachedMaterial();
  27218. }
  27219. };
  27220. if (!_this.url) {
  27221. _this._delayedOnLoad = load;
  27222. _this._delayedOnError = onError;
  27223. return _this;
  27224. }
  27225. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  27226. if (!_this._texture) {
  27227. if (!scene.useDelayedTextureLoading) {
  27228. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  27229. if (deleteBuffer) {
  27230. delete _this._buffer;
  27231. }
  27232. }
  27233. else {
  27234. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27235. _this._delayedOnLoad = load;
  27236. _this._delayedOnError = onError;
  27237. }
  27238. }
  27239. else {
  27240. if (_this._texture.isReady) {
  27241. BABYLON.Tools.SetImmediate(function () { return load(); });
  27242. }
  27243. else {
  27244. _this._texture.onLoadedObservable.add(load);
  27245. }
  27246. }
  27247. return _this;
  27248. }
  27249. Object.defineProperty(Texture.prototype, "noMipmap", {
  27250. get: function () {
  27251. return this._noMipmap;
  27252. },
  27253. enumerable: true,
  27254. configurable: true
  27255. });
  27256. Object.defineProperty(Texture.prototype, "isBlocking", {
  27257. get: function () {
  27258. return this._isBlocking;
  27259. },
  27260. set: function (value) {
  27261. this._isBlocking = value;
  27262. },
  27263. enumerable: true,
  27264. configurable: true
  27265. });
  27266. Object.defineProperty(Texture.prototype, "samplingMode", {
  27267. get: function () {
  27268. return this._samplingMode;
  27269. },
  27270. enumerable: true,
  27271. configurable: true
  27272. });
  27273. Texture.prototype.updateURL = function (url) {
  27274. this.url = url;
  27275. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27276. this.delayLoad();
  27277. };
  27278. Texture.prototype.delayLoad = function () {
  27279. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27280. return;
  27281. }
  27282. var scene = this.getScene();
  27283. if (!scene) {
  27284. return;
  27285. }
  27286. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27287. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  27288. if (!this._texture) {
  27289. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  27290. if (this._deleteBuffer) {
  27291. delete this._buffer;
  27292. }
  27293. }
  27294. else {
  27295. if (this._delayedOnLoad) {
  27296. if (this._texture.isReady) {
  27297. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  27298. }
  27299. else {
  27300. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  27301. }
  27302. }
  27303. }
  27304. this._delayedOnLoad = null;
  27305. this._delayedOnError = null;
  27306. };
  27307. Texture.prototype.updateSamplingMode = function (samplingMode) {
  27308. if (!this._texture) {
  27309. return;
  27310. }
  27311. var scene = this.getScene();
  27312. if (!scene) {
  27313. return;
  27314. }
  27315. this._samplingMode = samplingMode;
  27316. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  27317. };
  27318. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  27319. x *= this.uScale;
  27320. y *= this.vScale;
  27321. x -= 0.5 * this.uScale;
  27322. y -= 0.5 * this.vScale;
  27323. z -= 0.5;
  27324. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  27325. t.x += 0.5 * this.uScale + this.uOffset;
  27326. t.y += 0.5 * this.vScale + this.vOffset;
  27327. t.z += 0.5;
  27328. };
  27329. Texture.prototype.getTextureMatrix = function () {
  27330. var _this = this;
  27331. if (this.uOffset === this._cachedUOffset &&
  27332. this.vOffset === this._cachedVOffset &&
  27333. this.uScale === this._cachedUScale &&
  27334. this.vScale === this._cachedVScale &&
  27335. this.uAng === this._cachedUAng &&
  27336. this.vAng === this._cachedVAng &&
  27337. this.wAng === this._cachedWAng) {
  27338. return this._cachedTextureMatrix;
  27339. }
  27340. this._cachedUOffset = this.uOffset;
  27341. this._cachedVOffset = this.vOffset;
  27342. this._cachedUScale = this.uScale;
  27343. this._cachedVScale = this.vScale;
  27344. this._cachedUAng = this.uAng;
  27345. this._cachedVAng = this.vAng;
  27346. this._cachedWAng = this.wAng;
  27347. if (!this._cachedTextureMatrix) {
  27348. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27349. this._rowGenerationMatrix = new BABYLON.Matrix();
  27350. this._t0 = BABYLON.Vector3.Zero();
  27351. this._t1 = BABYLON.Vector3.Zero();
  27352. this._t2 = BABYLON.Vector3.Zero();
  27353. }
  27354. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  27355. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  27356. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  27357. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  27358. this._t1.subtractInPlace(this._t0);
  27359. this._t2.subtractInPlace(this._t0);
  27360. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27361. this._cachedTextureMatrix.m[0] = this._t1.x;
  27362. this._cachedTextureMatrix.m[1] = this._t1.y;
  27363. this._cachedTextureMatrix.m[2] = this._t1.z;
  27364. this._cachedTextureMatrix.m[4] = this._t2.x;
  27365. this._cachedTextureMatrix.m[5] = this._t2.y;
  27366. this._cachedTextureMatrix.m[6] = this._t2.z;
  27367. this._cachedTextureMatrix.m[8] = this._t0.x;
  27368. this._cachedTextureMatrix.m[9] = this._t0.y;
  27369. this._cachedTextureMatrix.m[10] = this._t0.z;
  27370. var scene = this.getScene();
  27371. if (!scene) {
  27372. return this._cachedTextureMatrix;
  27373. }
  27374. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27375. return mat.hasTexture(_this);
  27376. });
  27377. return this._cachedTextureMatrix;
  27378. };
  27379. Texture.prototype.getReflectionTextureMatrix = function () {
  27380. var _this = this;
  27381. var scene = this.getScene();
  27382. if (!scene) {
  27383. return this._cachedTextureMatrix;
  27384. }
  27385. if (this.uOffset === this._cachedUOffset &&
  27386. this.vOffset === this._cachedVOffset &&
  27387. this.uScale === this._cachedUScale &&
  27388. this.vScale === this._cachedVScale &&
  27389. this.coordinatesMode === this._cachedCoordinatesMode) {
  27390. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  27391. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  27392. return this._cachedTextureMatrix;
  27393. }
  27394. }
  27395. else {
  27396. return this._cachedTextureMatrix;
  27397. }
  27398. }
  27399. if (!this._cachedTextureMatrix) {
  27400. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27401. }
  27402. if (!this._projectionModeMatrix) {
  27403. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  27404. }
  27405. this._cachedUOffset = this.uOffset;
  27406. this._cachedVOffset = this.vOffset;
  27407. this._cachedUScale = this.uScale;
  27408. this._cachedVScale = this.vScale;
  27409. this._cachedCoordinatesMode = this.coordinatesMode;
  27410. switch (this.coordinatesMode) {
  27411. case Texture.PLANAR_MODE:
  27412. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27413. this._cachedTextureMatrix[0] = this.uScale;
  27414. this._cachedTextureMatrix[5] = this.vScale;
  27415. this._cachedTextureMatrix[12] = this.uOffset;
  27416. this._cachedTextureMatrix[13] = this.vOffset;
  27417. break;
  27418. case Texture.PROJECTION_MODE:
  27419. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27420. this._projectionModeMatrix.m[0] = 0.5;
  27421. this._projectionModeMatrix.m[5] = -0.5;
  27422. this._projectionModeMatrix.m[10] = 0.0;
  27423. this._projectionModeMatrix.m[12] = 0.5;
  27424. this._projectionModeMatrix.m[13] = 0.5;
  27425. this._projectionModeMatrix.m[14] = 1.0;
  27426. this._projectionModeMatrix.m[15] = 1.0;
  27427. var projectionMatrix = scene.getProjectionMatrix();
  27428. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  27429. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27430. break;
  27431. default:
  27432. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27433. break;
  27434. }
  27435. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27436. return (mat.getActiveTextures().indexOf(_this) !== -1);
  27437. });
  27438. return this._cachedTextureMatrix;
  27439. };
  27440. Texture.prototype.clone = function () {
  27441. var _this = this;
  27442. return BABYLON.SerializationHelper.Clone(function () {
  27443. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27444. }, this);
  27445. };
  27446. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27447. get: function () {
  27448. if (!this._onLoadObservable) {
  27449. this._onLoadObservable = new BABYLON.Observable();
  27450. }
  27451. return this._onLoadObservable;
  27452. },
  27453. enumerable: true,
  27454. configurable: true
  27455. });
  27456. Texture.prototype.serialize = function () {
  27457. var serializationObject = _super.prototype.serialize.call(this);
  27458. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  27459. serializationObject.base64String = this._buffer;
  27460. serializationObject.name = serializationObject.name.replace("data:", "");
  27461. }
  27462. return serializationObject;
  27463. };
  27464. Texture.prototype.getClassName = function () {
  27465. return "Texture";
  27466. };
  27467. Texture.prototype.dispose = function () {
  27468. _super.prototype.dispose.call(this);
  27469. if (this.onLoadObservable) {
  27470. this.onLoadObservable.clear();
  27471. this._onLoadObservable = null;
  27472. }
  27473. this._delayedOnLoad = null;
  27474. this._delayedOnError = null;
  27475. };
  27476. // Statics
  27477. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27478. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27479. if (onLoad === void 0) { onLoad = null; }
  27480. if (onError === void 0) { onError = null; }
  27481. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27482. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27483. };
  27484. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27485. if (parsedTexture.customType) {
  27486. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27487. // Update Sampling Mode
  27488. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  27489. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  27490. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27491. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27492. }
  27493. }
  27494. return parsedCustomTexture;
  27495. }
  27496. if (parsedTexture.isCube) {
  27497. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27498. }
  27499. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27500. return null;
  27501. }
  27502. var texture = BABYLON.SerializationHelper.Parse(function () {
  27503. var generateMipMaps = true;
  27504. if (parsedTexture.noMipmap) {
  27505. generateMipMaps = false;
  27506. }
  27507. if (parsedTexture.mirrorPlane) {
  27508. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27509. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27510. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27511. return mirrorTexture;
  27512. }
  27513. else if (parsedTexture.isRenderTarget) {
  27514. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27515. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27516. return renderTargetTexture;
  27517. }
  27518. else {
  27519. var texture;
  27520. if (parsedTexture.base64String) {
  27521. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27522. }
  27523. else {
  27524. var url = rootUrl + parsedTexture.name;
  27525. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27526. url = parsedTexture.url;
  27527. }
  27528. texture = new Texture(url, scene, !generateMipMaps);
  27529. }
  27530. return texture;
  27531. }
  27532. }, parsedTexture, scene);
  27533. // Update Sampling Mode
  27534. if (parsedTexture.samplingMode) {
  27535. var sampling = parsedTexture.samplingMode;
  27536. if (texture._samplingMode !== sampling) {
  27537. texture.updateSamplingMode(sampling);
  27538. }
  27539. }
  27540. // Animations
  27541. if (parsedTexture.animations) {
  27542. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27543. var parsedAnimation = parsedTexture.animations[animationIndex];
  27544. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27545. }
  27546. }
  27547. return texture;
  27548. };
  27549. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27550. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27551. if (noMipmap === void 0) { noMipmap = false; }
  27552. if (invertY === void 0) { invertY = true; }
  27553. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27554. if (onLoad === void 0) { onLoad = null; }
  27555. if (onError === void 0) { onError = null; }
  27556. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27557. if (name.substr(0, 5) !== "data:") {
  27558. name = "data:" + name;
  27559. }
  27560. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27561. };
  27562. // Constants
  27563. Texture.NEAREST_SAMPLINGMODE = 1;
  27564. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27565. Texture.BILINEAR_SAMPLINGMODE = 2;
  27566. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27567. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27568. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27569. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27570. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27571. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27572. Texture.NEAREST_LINEAR = 7;
  27573. Texture.NEAREST_NEAREST = 8;
  27574. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27575. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27576. Texture.LINEAR_LINEAR = 11;
  27577. Texture.LINEAR_NEAREST = 12;
  27578. Texture.EXPLICIT_MODE = 0;
  27579. Texture.SPHERICAL_MODE = 1;
  27580. Texture.PLANAR_MODE = 2;
  27581. Texture.CUBIC_MODE = 3;
  27582. Texture.PROJECTION_MODE = 4;
  27583. Texture.SKYBOX_MODE = 5;
  27584. Texture.INVCUBIC_MODE = 6;
  27585. Texture.EQUIRECTANGULAR_MODE = 7;
  27586. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27587. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27588. Texture.CLAMP_ADDRESSMODE = 0;
  27589. Texture.WRAP_ADDRESSMODE = 1;
  27590. Texture.MIRROR_ADDRESSMODE = 2;
  27591. /**
  27592. * 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
  27593. */
  27594. Texture.UseSerializedUrlIfAny = false;
  27595. __decorate([
  27596. BABYLON.serialize()
  27597. ], Texture.prototype, "url", void 0);
  27598. __decorate([
  27599. BABYLON.serialize()
  27600. ], Texture.prototype, "uOffset", void 0);
  27601. __decorate([
  27602. BABYLON.serialize()
  27603. ], Texture.prototype, "vOffset", void 0);
  27604. __decorate([
  27605. BABYLON.serialize()
  27606. ], Texture.prototype, "uScale", void 0);
  27607. __decorate([
  27608. BABYLON.serialize()
  27609. ], Texture.prototype, "vScale", void 0);
  27610. __decorate([
  27611. BABYLON.serialize()
  27612. ], Texture.prototype, "uAng", void 0);
  27613. __decorate([
  27614. BABYLON.serialize()
  27615. ], Texture.prototype, "vAng", void 0);
  27616. __decorate([
  27617. BABYLON.serialize()
  27618. ], Texture.prototype, "wAng", void 0);
  27619. __decorate([
  27620. BABYLON.serialize()
  27621. ], Texture.prototype, "isBlocking", null);
  27622. return Texture;
  27623. }(BABYLON.BaseTexture));
  27624. BABYLON.Texture = Texture;
  27625. })(BABYLON || (BABYLON = {}));
  27626. //# sourceMappingURL=babylon.texture.js.map
  27627. var BABYLON;
  27628. (function (BABYLON) {
  27629. var _InstancesBatch = /** @class */ (function () {
  27630. function _InstancesBatch() {
  27631. this.mustReturn = false;
  27632. this.visibleInstances = new Array();
  27633. this.renderSelf = new Array();
  27634. }
  27635. return _InstancesBatch;
  27636. }());
  27637. BABYLON._InstancesBatch = _InstancesBatch;
  27638. var Mesh = /** @class */ (function (_super) {
  27639. __extends(Mesh, _super);
  27640. /**
  27641. * @constructor
  27642. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27643. * @param {Scene} scene The scene to add this mesh to.
  27644. * @param {Node} parent The parent of this mesh, if it has one
  27645. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27646. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27647. * When false, achieved by calling a clone(), also passing False.
  27648. * This will make creation of children, recursive.
  27649. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27650. */
  27651. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27652. if (scene === void 0) { scene = null; }
  27653. if (parent === void 0) { parent = null; }
  27654. if (source === void 0) { source = null; }
  27655. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27656. var _this = _super.call(this, name, scene) || this;
  27657. // Events
  27658. /**
  27659. * An event triggered before rendering the mesh
  27660. * @type {BABYLON.Observable}
  27661. */
  27662. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27663. /**
  27664. * An event triggered after rendering the mesh
  27665. * @type {BABYLON.Observable}
  27666. */
  27667. _this.onAfterRenderObservable = new BABYLON.Observable();
  27668. /**
  27669. * An event triggered before drawing the mesh
  27670. * @type {BABYLON.Observable}
  27671. */
  27672. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27673. // Members
  27674. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27675. _this.instances = new Array();
  27676. _this._LODLevels = new Array();
  27677. _this._visibleInstances = {};
  27678. _this._renderIdForInstances = new Array();
  27679. _this._batchCache = new _InstancesBatch();
  27680. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27681. // Use by builder only to know what orientation were the mesh build in.
  27682. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27683. _this.overrideMaterialSideOrientation = null;
  27684. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27685. // Will be used to save a source mesh reference, If any
  27686. _this._source = null;
  27687. scene = _this.getScene();
  27688. if (source) {
  27689. // Source mesh
  27690. _this._source = source;
  27691. // Geometry
  27692. if (source._geometry) {
  27693. source._geometry.applyToMesh(_this);
  27694. }
  27695. // Deep copy
  27696. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  27697. // Metadata
  27698. if (source.metadata && source.metadata.clone) {
  27699. _this.metadata = source.metadata.clone();
  27700. }
  27701. else {
  27702. _this.metadata = source.metadata;
  27703. }
  27704. // Tags
  27705. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27706. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27707. }
  27708. // Parent
  27709. _this.parent = source.parent;
  27710. // Pivot
  27711. _this.setPivotMatrix(source.getPivotMatrix());
  27712. _this.id = name + "." + source.id;
  27713. // Material
  27714. _this.material = source.material;
  27715. var index;
  27716. if (!doNotCloneChildren) {
  27717. // Children
  27718. var directDescendants = source.getDescendants(true);
  27719. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27720. var child = directDescendants[index_1];
  27721. if (child.clone) {
  27722. child.clone(name + "." + child.name, _this);
  27723. }
  27724. }
  27725. }
  27726. // Physics clone
  27727. var physicsEngine = _this.getScene().getPhysicsEngine();
  27728. if (clonePhysicsImpostor && physicsEngine) {
  27729. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27730. if (impostor) {
  27731. _this.physicsImpostor = impostor.clone(_this);
  27732. }
  27733. }
  27734. // Particles
  27735. for (index = 0; index < scene.particleSystems.length; index++) {
  27736. var system = scene.particleSystems[index];
  27737. if (system.emitter === source) {
  27738. system.clone(system.name, _this);
  27739. }
  27740. }
  27741. _this.computeWorldMatrix(true);
  27742. }
  27743. // Parent
  27744. if (parent !== null) {
  27745. _this.parent = parent;
  27746. }
  27747. return _this;
  27748. }
  27749. Object.defineProperty(Mesh, "FRONTSIDE", {
  27750. /**
  27751. * Mesh side orientation : usually the external or front surface
  27752. */
  27753. get: function () {
  27754. return Mesh._FRONTSIDE;
  27755. },
  27756. enumerable: true,
  27757. configurable: true
  27758. });
  27759. Object.defineProperty(Mesh, "BACKSIDE", {
  27760. /**
  27761. * Mesh side orientation : usually the internal or back surface
  27762. */
  27763. get: function () {
  27764. return Mesh._BACKSIDE;
  27765. },
  27766. enumerable: true,
  27767. configurable: true
  27768. });
  27769. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27770. /**
  27771. * Mesh side orientation : both internal and external or front and back surfaces
  27772. */
  27773. get: function () {
  27774. return Mesh._DOUBLESIDE;
  27775. },
  27776. enumerable: true,
  27777. configurable: true
  27778. });
  27779. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27780. /**
  27781. * Mesh side orientation : by default, `FRONTSIDE`
  27782. */
  27783. get: function () {
  27784. return Mesh._DEFAULTSIDE;
  27785. },
  27786. enumerable: true,
  27787. configurable: true
  27788. });
  27789. Object.defineProperty(Mesh, "NO_CAP", {
  27790. /**
  27791. * Mesh cap setting : no cap
  27792. */
  27793. get: function () {
  27794. return Mesh._NO_CAP;
  27795. },
  27796. enumerable: true,
  27797. configurable: true
  27798. });
  27799. Object.defineProperty(Mesh, "CAP_START", {
  27800. /**
  27801. * Mesh cap setting : one cap at the beginning of the mesh
  27802. */
  27803. get: function () {
  27804. return Mesh._CAP_START;
  27805. },
  27806. enumerable: true,
  27807. configurable: true
  27808. });
  27809. Object.defineProperty(Mesh, "CAP_END", {
  27810. /**
  27811. * Mesh cap setting : one cap at the end of the mesh
  27812. */
  27813. get: function () {
  27814. return Mesh._CAP_END;
  27815. },
  27816. enumerable: true,
  27817. configurable: true
  27818. });
  27819. Object.defineProperty(Mesh, "CAP_ALL", {
  27820. /**
  27821. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27822. */
  27823. get: function () {
  27824. return Mesh._CAP_ALL;
  27825. },
  27826. enumerable: true,
  27827. configurable: true
  27828. });
  27829. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27830. set: function (callback) {
  27831. if (this._onBeforeDrawObserver) {
  27832. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27833. }
  27834. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27835. },
  27836. enumerable: true,
  27837. configurable: true
  27838. });
  27839. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27840. get: function () {
  27841. return this._morphTargetManager;
  27842. },
  27843. set: function (value) {
  27844. if (this._morphTargetManager === value) {
  27845. return;
  27846. }
  27847. this._morphTargetManager = value;
  27848. this._syncGeometryWithMorphTargetManager();
  27849. },
  27850. enumerable: true,
  27851. configurable: true
  27852. });
  27853. Object.defineProperty(Mesh.prototype, "source", {
  27854. get: function () {
  27855. return this._source;
  27856. },
  27857. enumerable: true,
  27858. configurable: true
  27859. });
  27860. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27861. get: function () {
  27862. return this._unIndexed;
  27863. },
  27864. set: function (value) {
  27865. if (this._unIndexed !== value) {
  27866. this._unIndexed = value;
  27867. this._markSubMeshesAsAttributesDirty();
  27868. }
  27869. },
  27870. enumerable: true,
  27871. configurable: true
  27872. });
  27873. // Methods
  27874. /**
  27875. * Returns the string "Mesh".
  27876. */
  27877. Mesh.prototype.getClassName = function () {
  27878. return "Mesh";
  27879. };
  27880. /**
  27881. * Returns a string.
  27882. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27883. */
  27884. Mesh.prototype.toString = function (fullDetails) {
  27885. var ret = _super.prototype.toString.call(this, fullDetails);
  27886. ret += ", n vertices: " + this.getTotalVertices();
  27887. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27888. if (this.animations) {
  27889. for (var i = 0; i < this.animations.length; i++) {
  27890. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  27891. }
  27892. }
  27893. if (fullDetails) {
  27894. if (this._geometry) {
  27895. var ib = this.getIndices();
  27896. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27897. if (vb && ib) {
  27898. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  27899. }
  27900. }
  27901. else {
  27902. ret += ", flat shading: UNKNOWN";
  27903. }
  27904. }
  27905. return ret;
  27906. };
  27907. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  27908. /**
  27909. * True if the mesh has some Levels Of Details (LOD).
  27910. * Returns a boolean.
  27911. */
  27912. get: function () {
  27913. return this._LODLevels.length > 0;
  27914. },
  27915. enumerable: true,
  27916. configurable: true
  27917. });
  27918. /**
  27919. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  27920. * @returns an array of {BABYLON.MeshLODLevel}
  27921. */
  27922. Mesh.prototype.getLODLevels = function () {
  27923. return this._LODLevels;
  27924. };
  27925. Mesh.prototype._sortLODLevels = function () {
  27926. this._LODLevels.sort(function (a, b) {
  27927. if (a.distance < b.distance) {
  27928. return 1;
  27929. }
  27930. if (a.distance > b.distance) {
  27931. return -1;
  27932. }
  27933. return 0;
  27934. });
  27935. };
  27936. /**
  27937. * Add a mesh as LOD level triggered at the given distance.
  27938. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27939. * @param {number} distance The distance from the center of the object to show this level
  27940. * @param {Mesh} mesh The mesh to be added as LOD level
  27941. * @return {Mesh} This mesh (for chaining)
  27942. */
  27943. Mesh.prototype.addLODLevel = function (distance, mesh) {
  27944. if (mesh && mesh._masterMesh) {
  27945. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  27946. return this;
  27947. }
  27948. var level = new BABYLON.MeshLODLevel(distance, mesh);
  27949. this._LODLevels.push(level);
  27950. if (mesh) {
  27951. mesh._masterMesh = this;
  27952. }
  27953. this._sortLODLevels();
  27954. return this;
  27955. };
  27956. /**
  27957. * Returns the LOD level mesh at the passed distance or null if not found.
  27958. * It is related to the method `addLODLevel(distance, mesh)`.
  27959. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27960. * Returns an object Mesh or `null`.
  27961. */
  27962. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  27963. for (var index = 0; index < this._LODLevels.length; index++) {
  27964. var level = this._LODLevels[index];
  27965. if (level.distance === distance) {
  27966. return level.mesh;
  27967. }
  27968. }
  27969. return null;
  27970. };
  27971. /**
  27972. * Remove a mesh from the LOD array
  27973. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27974. * @param {Mesh} mesh The mesh to be removed.
  27975. * @return {Mesh} This mesh (for chaining)
  27976. */
  27977. Mesh.prototype.removeLODLevel = function (mesh) {
  27978. for (var index = 0; index < this._LODLevels.length; index++) {
  27979. if (this._LODLevels[index].mesh === mesh) {
  27980. this._LODLevels.splice(index, 1);
  27981. if (mesh) {
  27982. mesh._masterMesh = null;
  27983. }
  27984. }
  27985. }
  27986. this._sortLODLevels();
  27987. return this;
  27988. };
  27989. /**
  27990. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  27991. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27992. */
  27993. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  27994. if (!this._LODLevels || this._LODLevels.length === 0) {
  27995. return this;
  27996. }
  27997. var bSphere;
  27998. if (boundingSphere) {
  27999. bSphere = boundingSphere;
  28000. }
  28001. else {
  28002. var boundingInfo = this.getBoundingInfo();
  28003. bSphere = boundingInfo.boundingSphere;
  28004. }
  28005. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  28006. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  28007. if (this.onLODLevelSelection) {
  28008. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  28009. }
  28010. return this;
  28011. }
  28012. for (var index = 0; index < this._LODLevels.length; index++) {
  28013. var level = this._LODLevels[index];
  28014. if (level.distance < distanceToCamera) {
  28015. if (level.mesh) {
  28016. level.mesh._preActivate();
  28017. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  28018. }
  28019. if (this.onLODLevelSelection) {
  28020. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  28021. }
  28022. return level.mesh;
  28023. }
  28024. }
  28025. if (this.onLODLevelSelection) {
  28026. this.onLODLevelSelection(distanceToCamera, this, this);
  28027. }
  28028. return this;
  28029. };
  28030. Object.defineProperty(Mesh.prototype, "geometry", {
  28031. /**
  28032. * Returns the mesh internal Geometry object.
  28033. */
  28034. get: function () {
  28035. return this._geometry;
  28036. },
  28037. enumerable: true,
  28038. configurable: true
  28039. });
  28040. /**
  28041. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  28042. */
  28043. Mesh.prototype.getTotalVertices = function () {
  28044. if (this._geometry === null || this._geometry === undefined) {
  28045. return 0;
  28046. }
  28047. return this._geometry.getTotalVertices();
  28048. };
  28049. /**
  28050. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  28051. * 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.
  28052. * You can force the copy with forceCopy === true
  28053. * Returns null if the mesh has no geometry or no vertex buffer.
  28054. * Possible `kind` values :
  28055. * - BABYLON.VertexBuffer.PositionKind
  28056. * - BABYLON.VertexBuffer.UVKind
  28057. * - BABYLON.VertexBuffer.UV2Kind
  28058. * - BABYLON.VertexBuffer.UV3Kind
  28059. * - BABYLON.VertexBuffer.UV4Kind
  28060. * - BABYLON.VertexBuffer.UV5Kind
  28061. * - BABYLON.VertexBuffer.UV6Kind
  28062. * - BABYLON.VertexBuffer.ColorKind
  28063. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28064. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28065. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28066. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28067. */
  28068. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  28069. if (!this._geometry) {
  28070. return null;
  28071. }
  28072. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  28073. };
  28074. /**
  28075. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  28076. * Returns `null` if the mesh has no geometry.
  28077. * Possible `kind` values :
  28078. * - BABYLON.VertexBuffer.PositionKind
  28079. * - BABYLON.VertexBuffer.UVKind
  28080. * - BABYLON.VertexBuffer.UV2Kind
  28081. * - BABYLON.VertexBuffer.UV3Kind
  28082. * - BABYLON.VertexBuffer.UV4Kind
  28083. * - BABYLON.VertexBuffer.UV5Kind
  28084. * - BABYLON.VertexBuffer.UV6Kind
  28085. * - BABYLON.VertexBuffer.ColorKind
  28086. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28087. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28088. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28089. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28090. */
  28091. Mesh.prototype.getVertexBuffer = function (kind) {
  28092. if (!this._geometry) {
  28093. return null;
  28094. }
  28095. return this._geometry.getVertexBuffer(kind);
  28096. };
  28097. /**
  28098. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  28099. * Possible `kind` values :
  28100. * - BABYLON.VertexBuffer.PositionKind
  28101. * - BABYLON.VertexBuffer.UVKind
  28102. * - BABYLON.VertexBuffer.UV2Kind
  28103. * - BABYLON.VertexBuffer.UV3Kind
  28104. * - BABYLON.VertexBuffer.UV4Kind
  28105. * - BABYLON.VertexBuffer.UV5Kind
  28106. * - BABYLON.VertexBuffer.UV6Kind
  28107. * - BABYLON.VertexBuffer.ColorKind
  28108. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28109. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28110. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28111. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28112. */
  28113. Mesh.prototype.isVerticesDataPresent = function (kind) {
  28114. if (!this._geometry) {
  28115. if (this._delayInfo) {
  28116. return this._delayInfo.indexOf(kind) !== -1;
  28117. }
  28118. return false;
  28119. }
  28120. return this._geometry.isVerticesDataPresent(kind);
  28121. };
  28122. /**
  28123. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  28124. * Possible `kind` values :
  28125. * - BABYLON.VertexBuffer.PositionKind
  28126. * - BABYLON.VertexBuffer.UVKind
  28127. * - BABYLON.VertexBuffer.UV2Kind
  28128. * - BABYLON.VertexBuffer.UV3Kind
  28129. * - BABYLON.VertexBuffer.UV4Kind
  28130. * - BABYLON.VertexBuffer.UV5Kind
  28131. * - BABYLON.VertexBuffer.UV6Kind
  28132. * - BABYLON.VertexBuffer.ColorKind
  28133. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28134. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28135. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28136. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28137. */
  28138. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  28139. if (!this._geometry) {
  28140. if (this._delayInfo) {
  28141. return this._delayInfo.indexOf(kind) !== -1;
  28142. }
  28143. return false;
  28144. }
  28145. return this._geometry.isVertexBufferUpdatable(kind);
  28146. };
  28147. /**
  28148. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  28149. * Possible `kind` values :
  28150. * - BABYLON.VertexBuffer.PositionKind
  28151. * - BABYLON.VertexBuffer.UVKind
  28152. * - BABYLON.VertexBuffer.UV2Kind
  28153. * - BABYLON.VertexBuffer.UV3Kind
  28154. * - BABYLON.VertexBuffer.UV4Kind
  28155. * - BABYLON.VertexBuffer.UV5Kind
  28156. * - BABYLON.VertexBuffer.UV6Kind
  28157. * - BABYLON.VertexBuffer.ColorKind
  28158. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28159. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28160. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28161. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28162. */
  28163. Mesh.prototype.getVerticesDataKinds = function () {
  28164. if (!this._geometry) {
  28165. var result = new Array();
  28166. if (this._delayInfo) {
  28167. this._delayInfo.forEach(function (kind, index, array) {
  28168. result.push(kind);
  28169. });
  28170. }
  28171. return result;
  28172. }
  28173. return this._geometry.getVerticesDataKinds();
  28174. };
  28175. /**
  28176. * Returns a positive integer : the total number of indices in this mesh geometry.
  28177. * Returns zero if the mesh has no geometry.
  28178. */
  28179. Mesh.prototype.getTotalIndices = function () {
  28180. if (!this._geometry) {
  28181. return 0;
  28182. }
  28183. return this._geometry.getTotalIndices();
  28184. };
  28185. /**
  28186. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  28187. * 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.
  28188. * Returns an empty array if the mesh has no geometry.
  28189. */
  28190. Mesh.prototype.getIndices = function (copyWhenShared) {
  28191. if (!this._geometry) {
  28192. return [];
  28193. }
  28194. return this._geometry.getIndices(copyWhenShared);
  28195. };
  28196. Object.defineProperty(Mesh.prototype, "isBlocked", {
  28197. get: function () {
  28198. return this._masterMesh !== null && this._masterMesh !== undefined;
  28199. },
  28200. enumerable: true,
  28201. configurable: true
  28202. });
  28203. /**
  28204. * Determine if the current mesh is ready to be rendered
  28205. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  28206. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  28207. * @returns true if all associated assets are ready (material, textures, shaders)
  28208. */
  28209. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  28210. if (completeCheck === void 0) { completeCheck = false; }
  28211. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  28212. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28213. return false;
  28214. }
  28215. if (!_super.prototype.isReady.call(this, completeCheck)) {
  28216. return false;
  28217. }
  28218. if (!this.subMeshes || this.subMeshes.length === 0) {
  28219. return true;
  28220. }
  28221. if (!completeCheck) {
  28222. return true;
  28223. }
  28224. var engine = this.getEngine();
  28225. var scene = this.getScene();
  28226. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  28227. this.computeWorldMatrix();
  28228. var mat = this.material || scene.defaultMaterial;
  28229. if (mat) {
  28230. if (mat.storeEffectOnSubMeshes) {
  28231. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28232. var subMesh = _a[_i];
  28233. var effectiveMaterial = subMesh.getMaterial();
  28234. if (effectiveMaterial) {
  28235. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28236. return false;
  28237. }
  28238. }
  28239. }
  28240. }
  28241. else {
  28242. if (!mat.isReady(this, hardwareInstancedRendering)) {
  28243. return false;
  28244. }
  28245. }
  28246. }
  28247. // Shadows
  28248. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  28249. var light = _c[_b];
  28250. var generator = light.getShadowGenerator();
  28251. if (generator) {
  28252. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  28253. var subMesh = _e[_d];
  28254. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  28255. return false;
  28256. }
  28257. }
  28258. }
  28259. }
  28260. // LOD
  28261. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  28262. var lod = _g[_f];
  28263. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  28264. return false;
  28265. }
  28266. }
  28267. return true;
  28268. };
  28269. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  28270. /**
  28271. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  28272. * This property is pertinent only for updatable parametric shapes.
  28273. */
  28274. get: function () {
  28275. return this._areNormalsFrozen;
  28276. },
  28277. enumerable: true,
  28278. configurable: true
  28279. });
  28280. /**
  28281. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28282. * It has no effect at all on other shapes.
  28283. * It prevents the mesh normals from being recomputed on next `positions` array update.
  28284. * Returns the Mesh.
  28285. */
  28286. Mesh.prototype.freezeNormals = function () {
  28287. this._areNormalsFrozen = true;
  28288. return this;
  28289. };
  28290. /**
  28291. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28292. * It has no effect at all on other shapes.
  28293. * It reactivates the mesh normals computation if it was previously frozen.
  28294. * Returns the Mesh.
  28295. */
  28296. Mesh.prototype.unfreezeNormals = function () {
  28297. this._areNormalsFrozen = false;
  28298. return this;
  28299. };
  28300. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  28301. /**
  28302. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  28303. */
  28304. set: function (count) {
  28305. this._overridenInstanceCount = count;
  28306. },
  28307. enumerable: true,
  28308. configurable: true
  28309. });
  28310. // Methods
  28311. Mesh.prototype._preActivate = function () {
  28312. var sceneRenderId = this.getScene().getRenderId();
  28313. if (this._preActivateId === sceneRenderId) {
  28314. return this;
  28315. }
  28316. this._preActivateId = sceneRenderId;
  28317. this._visibleInstances = null;
  28318. return this;
  28319. };
  28320. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  28321. if (this._visibleInstances) {
  28322. this._visibleInstances.intermediateDefaultRenderId = renderId;
  28323. }
  28324. return this;
  28325. };
  28326. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  28327. if (!this._visibleInstances) {
  28328. this._visibleInstances = {};
  28329. this._visibleInstances.defaultRenderId = renderId;
  28330. this._visibleInstances.selfDefaultRenderId = this._renderId;
  28331. }
  28332. if (!this._visibleInstances[renderId]) {
  28333. this._visibleInstances[renderId] = new Array();
  28334. }
  28335. this._visibleInstances[renderId].push(instance);
  28336. return this;
  28337. };
  28338. /**
  28339. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  28340. * This means the mesh underlying bounding box and sphere are recomputed.
  28341. * Returns the Mesh.
  28342. */
  28343. Mesh.prototype.refreshBoundingInfo = function () {
  28344. return this._refreshBoundingInfo(false);
  28345. };
  28346. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  28347. if (this._boundingInfo && this._boundingInfo.isLocked) {
  28348. return this;
  28349. }
  28350. var data = this._getPositionData(applySkeleton);
  28351. if (data) {
  28352. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  28353. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28354. }
  28355. if (this.subMeshes) {
  28356. for (var index = 0; index < this.subMeshes.length; index++) {
  28357. this.subMeshes[index].refreshBoundingInfo();
  28358. }
  28359. }
  28360. this._updateBoundingInfo();
  28361. return this;
  28362. };
  28363. Mesh.prototype._getPositionData = function (applySkeleton) {
  28364. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28365. if (data && applySkeleton && this.skeleton) {
  28366. data = BABYLON.Tools.Slice(data);
  28367. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28368. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28369. if (matricesWeightsData && matricesIndicesData) {
  28370. var needExtras = this.numBoneInfluencers > 4;
  28371. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28372. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28373. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  28374. var tempVector = BABYLON.Tmp.Vector3[0];
  28375. var finalMatrix = BABYLON.Tmp.Matrix[0];
  28376. var tempMatrix = BABYLON.Tmp.Matrix[1];
  28377. var matWeightIdx = 0;
  28378. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  28379. finalMatrix.reset();
  28380. var inf;
  28381. var weight;
  28382. for (inf = 0; inf < 4; inf++) {
  28383. weight = matricesWeightsData[matWeightIdx + inf];
  28384. if (weight <= 0)
  28385. break;
  28386. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28387. finalMatrix.addToSelf(tempMatrix);
  28388. }
  28389. if (needExtras) {
  28390. for (inf = 0; inf < 4; inf++) {
  28391. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28392. if (weight <= 0)
  28393. break;
  28394. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28395. finalMatrix.addToSelf(tempMatrix);
  28396. }
  28397. }
  28398. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  28399. tempVector.toArray(data, index);
  28400. }
  28401. }
  28402. }
  28403. return data;
  28404. };
  28405. Mesh.prototype._createGlobalSubMesh = function (force) {
  28406. var totalVertices = this.getTotalVertices();
  28407. if (!totalVertices || !this.getIndices()) {
  28408. return null;
  28409. }
  28410. // Check if we need to recreate the submeshes
  28411. if (this.subMeshes && this.subMeshes.length > 0) {
  28412. var ib = this.getIndices();
  28413. if (!ib) {
  28414. return null;
  28415. }
  28416. var totalIndices = ib.length;
  28417. var needToRecreate = false;
  28418. if (force) {
  28419. needToRecreate = true;
  28420. }
  28421. else {
  28422. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28423. var submesh = _a[_i];
  28424. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  28425. needToRecreate = true;
  28426. break;
  28427. }
  28428. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  28429. needToRecreate = true;
  28430. break;
  28431. }
  28432. }
  28433. }
  28434. if (!needToRecreate) {
  28435. return this.subMeshes[0];
  28436. }
  28437. }
  28438. this.releaseSubMeshes();
  28439. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  28440. };
  28441. Mesh.prototype.subdivide = function (count) {
  28442. if (count < 1) {
  28443. return;
  28444. }
  28445. var totalIndices = this.getTotalIndices();
  28446. var subdivisionSize = (totalIndices / count) | 0;
  28447. var offset = 0;
  28448. // Ensure that subdivisionSize is a multiple of 3
  28449. while (subdivisionSize % 3 !== 0) {
  28450. subdivisionSize++;
  28451. }
  28452. this.releaseSubMeshes();
  28453. for (var index = 0; index < count; index++) {
  28454. if (offset >= totalIndices) {
  28455. break;
  28456. }
  28457. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  28458. offset += subdivisionSize;
  28459. }
  28460. this.synchronizeInstances();
  28461. };
  28462. /**
  28463. * Sets the vertex data of the mesh geometry for the requested `kind`.
  28464. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  28465. * The `data` are either a numeric array either a Float32Array.
  28466. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  28467. * 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).
  28468. * Note that a new underlying VertexBuffer object is created each call.
  28469. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  28470. *
  28471. * Possible `kind` values :
  28472. * - BABYLON.VertexBuffer.PositionKind
  28473. * - BABYLON.VertexBuffer.UVKind
  28474. * - BABYLON.VertexBuffer.UV2Kind
  28475. * - BABYLON.VertexBuffer.UV3Kind
  28476. * - BABYLON.VertexBuffer.UV4Kind
  28477. * - BABYLON.VertexBuffer.UV5Kind
  28478. * - BABYLON.VertexBuffer.UV6Kind
  28479. * - BABYLON.VertexBuffer.ColorKind
  28480. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28481. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28482. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28483. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28484. *
  28485. * Returns the Mesh.
  28486. */
  28487. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28488. if (updatable === void 0) { updatable = false; }
  28489. if (!this._geometry) {
  28490. var vertexData = new BABYLON.VertexData();
  28491. vertexData.set(data, kind);
  28492. var scene = this.getScene();
  28493. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28494. }
  28495. else {
  28496. this._geometry.setVerticesData(kind, data, updatable, stride);
  28497. }
  28498. return this;
  28499. };
  28500. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28501. if (updatable === void 0) { updatable = true; }
  28502. var vb = this.getVertexBuffer(kind);
  28503. if (!vb || vb.isUpdatable() === updatable) {
  28504. return;
  28505. }
  28506. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28507. };
  28508. /**
  28509. * Sets the mesh VertexBuffer.
  28510. * Returns the Mesh.
  28511. */
  28512. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28513. if (!this._geometry) {
  28514. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28515. }
  28516. this._geometry.setVerticesBuffer(buffer);
  28517. return this;
  28518. };
  28519. /**
  28520. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28521. * If the mesh has no geometry, it is simply returned as it is.
  28522. * The `data` are either a numeric array either a Float32Array.
  28523. * No new underlying VertexBuffer object is created.
  28524. * 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.
  28525. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28526. *
  28527. * Possible `kind` values :
  28528. * - BABYLON.VertexBuffer.PositionKind
  28529. * - BABYLON.VertexBuffer.UVKind
  28530. * - BABYLON.VertexBuffer.UV2Kind
  28531. * - BABYLON.VertexBuffer.UV3Kind
  28532. * - BABYLON.VertexBuffer.UV4Kind
  28533. * - BABYLON.VertexBuffer.UV5Kind
  28534. * - BABYLON.VertexBuffer.UV6Kind
  28535. * - BABYLON.VertexBuffer.ColorKind
  28536. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28537. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28538. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28539. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28540. *
  28541. * Returns the Mesh.
  28542. */
  28543. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28544. if (!this._geometry) {
  28545. return this;
  28546. }
  28547. if (!makeItUnique) {
  28548. this._geometry.updateVerticesData(kind, data, updateExtends);
  28549. }
  28550. else {
  28551. this.makeGeometryUnique();
  28552. this.updateVerticesData(kind, data, updateExtends, false);
  28553. }
  28554. return this;
  28555. };
  28556. /**
  28557. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28558. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28559. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28560. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28561. * Returns the Mesh.
  28562. */
  28563. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28564. if (computeNormals === void 0) { computeNormals = true; }
  28565. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28566. if (!positions) {
  28567. return this;
  28568. }
  28569. positionFunction(positions);
  28570. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28571. if (computeNormals) {
  28572. var indices = this.getIndices();
  28573. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28574. if (!normals) {
  28575. return this;
  28576. }
  28577. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28578. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28579. }
  28580. return this;
  28581. };
  28582. /**
  28583. * Creates a un-shared specific occurence of the geometry for the mesh.
  28584. * Returns the Mesh.
  28585. */
  28586. Mesh.prototype.makeGeometryUnique = function () {
  28587. if (!this._geometry) {
  28588. return this;
  28589. }
  28590. var oldGeometry = this._geometry;
  28591. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28592. oldGeometry.releaseForMesh(this, true);
  28593. geometry.applyToMesh(this);
  28594. return this;
  28595. };
  28596. /**
  28597. * Sets the mesh indices.
  28598. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28599. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28600. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28601. * This method creates a new index buffer each call.
  28602. * Returns the Mesh.
  28603. */
  28604. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28605. if (totalVertices === void 0) { totalVertices = null; }
  28606. if (updatable === void 0) { updatable = false; }
  28607. if (!this._geometry) {
  28608. var vertexData = new BABYLON.VertexData();
  28609. vertexData.indices = indices;
  28610. var scene = this.getScene();
  28611. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28612. }
  28613. else {
  28614. this._geometry.setIndices(indices, totalVertices, updatable);
  28615. }
  28616. return this;
  28617. };
  28618. /**
  28619. * Update the current index buffer
  28620. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28621. * Returns the Mesh.
  28622. */
  28623. Mesh.prototype.updateIndices = function (indices, offset) {
  28624. if (!this._geometry) {
  28625. return this;
  28626. }
  28627. this._geometry.updateIndices(indices, offset);
  28628. return this;
  28629. };
  28630. /**
  28631. * Invert the geometry to move from a right handed system to a left handed one.
  28632. * Returns the Mesh.
  28633. */
  28634. Mesh.prototype.toLeftHanded = function () {
  28635. if (!this._geometry) {
  28636. return this;
  28637. }
  28638. this._geometry.toLeftHanded();
  28639. return this;
  28640. };
  28641. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28642. if (!this._geometry) {
  28643. return this;
  28644. }
  28645. var engine = this.getScene().getEngine();
  28646. // Wireframe
  28647. var indexToBind;
  28648. if (this._unIndexed) {
  28649. indexToBind = null;
  28650. }
  28651. else {
  28652. switch (fillMode) {
  28653. case BABYLON.Material.PointFillMode:
  28654. indexToBind = null;
  28655. break;
  28656. case BABYLON.Material.WireFrameFillMode:
  28657. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28658. break;
  28659. default:
  28660. case BABYLON.Material.TriangleFillMode:
  28661. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28662. break;
  28663. }
  28664. }
  28665. // VBOs
  28666. this._geometry._bind(effect, indexToBind);
  28667. return this;
  28668. };
  28669. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28670. if (alternate === void 0) { alternate = false; }
  28671. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28672. return this;
  28673. }
  28674. this.onBeforeDrawObservable.notifyObservers(this);
  28675. var scene = this.getScene();
  28676. var engine = scene.getEngine();
  28677. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28678. // or triangles as points
  28679. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28680. }
  28681. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28682. // Triangles as wireframe
  28683. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28684. }
  28685. else {
  28686. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28687. }
  28688. if (scene._isAlternateRenderingEnabled && !alternate) {
  28689. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28690. if (!effect || !scene.activeCamera) {
  28691. return this;
  28692. }
  28693. scene._switchToAlternateCameraConfiguration(true);
  28694. this._effectiveMaterial.bindView(effect);
  28695. this._effectiveMaterial.bindViewProjection(effect);
  28696. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28697. this._draw(subMesh, fillMode, instancesCount, true);
  28698. engine.setViewport(scene.activeCamera.viewport);
  28699. scene._switchToAlternateCameraConfiguration(false);
  28700. this._effectiveMaterial.bindView(effect);
  28701. this._effectiveMaterial.bindViewProjection(effect);
  28702. }
  28703. return this;
  28704. };
  28705. /**
  28706. * Registers for this mesh a javascript function called just before the rendering process.
  28707. * This function is passed the current mesh.
  28708. * Return the Mesh.
  28709. */
  28710. Mesh.prototype.registerBeforeRender = function (func) {
  28711. this.onBeforeRenderObservable.add(func);
  28712. return this;
  28713. };
  28714. /**
  28715. * Disposes a previously registered javascript function called before the rendering.
  28716. * This function is passed the current mesh.
  28717. * Returns the Mesh.
  28718. */
  28719. Mesh.prototype.unregisterBeforeRender = function (func) {
  28720. this.onBeforeRenderObservable.removeCallback(func);
  28721. return this;
  28722. };
  28723. /**
  28724. * Registers for this mesh a javascript function called just after the rendering is complete.
  28725. * This function is passed the current mesh.
  28726. * Returns the Mesh.
  28727. */
  28728. Mesh.prototype.registerAfterRender = function (func) {
  28729. this.onAfterRenderObservable.add(func);
  28730. return this;
  28731. };
  28732. /**
  28733. * Disposes a previously registered javascript function called after the rendering.
  28734. * This function is passed the current mesh.
  28735. * Return the Mesh.
  28736. */
  28737. Mesh.prototype.unregisterAfterRender = function (func) {
  28738. this.onAfterRenderObservable.removeCallback(func);
  28739. return this;
  28740. };
  28741. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28742. var scene = this.getScene();
  28743. this._batchCache.mustReturn = false;
  28744. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28745. this._batchCache.visibleInstances[subMeshId] = null;
  28746. if (this._visibleInstances) {
  28747. var currentRenderId = scene.getRenderId();
  28748. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28749. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28750. var selfRenderId = this._renderId;
  28751. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28752. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28753. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28754. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28755. }
  28756. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28757. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28758. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28759. this._batchCache.mustReturn = true;
  28760. return this._batchCache;
  28761. }
  28762. if (currentRenderId !== selfRenderId) {
  28763. this._batchCache.renderSelf[subMeshId] = false;
  28764. }
  28765. }
  28766. this._renderIdForInstances[subMeshId] = currentRenderId;
  28767. }
  28768. return this._batchCache;
  28769. };
  28770. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28771. var visibleInstances = batch.visibleInstances[subMesh._id];
  28772. if (!visibleInstances) {
  28773. return this;
  28774. }
  28775. var matricesCount = visibleInstances.length + 1;
  28776. var bufferSize = matricesCount * 16 * 4;
  28777. var currentInstancesBufferSize = this._instancesBufferSize;
  28778. var instancesBuffer = this._instancesBuffer;
  28779. while (this._instancesBufferSize < bufferSize) {
  28780. this._instancesBufferSize *= 2;
  28781. }
  28782. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28783. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28784. }
  28785. var offset = 0;
  28786. var instancesCount = 0;
  28787. var world = this.getWorldMatrix();
  28788. if (batch.renderSelf[subMesh._id]) {
  28789. world.copyToArray(this._instancesData, offset);
  28790. offset += 16;
  28791. instancesCount++;
  28792. }
  28793. if (visibleInstances) {
  28794. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28795. var instance = visibleInstances[instanceIndex];
  28796. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28797. offset += 16;
  28798. instancesCount++;
  28799. }
  28800. }
  28801. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28802. if (instancesBuffer) {
  28803. instancesBuffer.dispose();
  28804. }
  28805. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28806. this._instancesBuffer = instancesBuffer;
  28807. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28808. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28809. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28810. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28811. }
  28812. else {
  28813. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28814. }
  28815. this._bind(subMesh, effect, fillMode);
  28816. this._draw(subMesh, fillMode, instancesCount);
  28817. engine.unbindInstanceAttributes();
  28818. return this;
  28819. };
  28820. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28821. var scene = this.getScene();
  28822. var engine = scene.getEngine();
  28823. if (hardwareInstancedRendering) {
  28824. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28825. }
  28826. else {
  28827. if (batch.renderSelf[subMesh._id]) {
  28828. // Draw
  28829. if (onBeforeDraw) {
  28830. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28831. }
  28832. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28833. }
  28834. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28835. if (visibleInstancesForSubMesh) {
  28836. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28837. var instance = visibleInstancesForSubMesh[instanceIndex];
  28838. // World
  28839. var world = instance.getWorldMatrix();
  28840. if (onBeforeDraw) {
  28841. onBeforeDraw(true, world, effectiveMaterial);
  28842. }
  28843. // Draw
  28844. this._draw(subMesh, fillMode);
  28845. }
  28846. }
  28847. }
  28848. return this;
  28849. };
  28850. /**
  28851. * Triggers the draw call for the mesh.
  28852. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28853. * Returns the Mesh.
  28854. */
  28855. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28856. this.checkOcclusionQuery();
  28857. if (this._isOccluded) {
  28858. return this;
  28859. }
  28860. var scene = this.getScene();
  28861. // Managing instances
  28862. var batch = this._getInstancesRenderList(subMesh._id);
  28863. if (batch.mustReturn) {
  28864. return this;
  28865. }
  28866. // Checking geometry state
  28867. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28868. return this;
  28869. }
  28870. this.onBeforeRenderObservable.notifyObservers(this);
  28871. var engine = scene.getEngine();
  28872. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28873. // Material
  28874. var material = subMesh.getMaterial();
  28875. if (!material) {
  28876. return this;
  28877. }
  28878. this._effectiveMaterial = material;
  28879. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28880. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28881. return this;
  28882. }
  28883. }
  28884. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28885. return this;
  28886. }
  28887. // Alpha mode
  28888. if (enableAlphaMode) {
  28889. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28890. }
  28891. // Outline - step 1
  28892. var savedDepthWrite = engine.getDepthWrite();
  28893. if (this.renderOutline) {
  28894. engine.setDepthWrite(false);
  28895. scene.getOutlineRenderer().render(subMesh, batch);
  28896. engine.setDepthWrite(savedDepthWrite);
  28897. }
  28898. var effect;
  28899. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28900. effect = subMesh.effect;
  28901. }
  28902. else {
  28903. effect = this._effectiveMaterial.getEffect();
  28904. }
  28905. if (!effect) {
  28906. return this;
  28907. }
  28908. var sideOrientation = this.overrideMaterialSideOrientation;
  28909. if (sideOrientation == null) {
  28910. sideOrientation = this._effectiveMaterial.sideOrientation;
  28911. if (this._getWorldMatrixDeterminant() < 0) {
  28912. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  28913. }
  28914. }
  28915. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  28916. if (this._effectiveMaterial.forceDepthWrite) {
  28917. engine.setDepthWrite(true);
  28918. }
  28919. // Bind
  28920. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  28921. if (!hardwareInstancedRendering) {
  28922. this._bind(subMesh, effect, fillMode);
  28923. }
  28924. var world = this.getWorldMatrix();
  28925. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28926. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  28927. }
  28928. else {
  28929. this._effectiveMaterial.bind(world, this);
  28930. }
  28931. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  28932. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  28933. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28934. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  28935. }
  28936. // Draw
  28937. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28938. // Unbind
  28939. this._effectiveMaterial.unbind();
  28940. // Outline - step 2
  28941. if (this.renderOutline && savedDepthWrite) {
  28942. engine.setDepthWrite(true);
  28943. engine.setColorWrite(false);
  28944. scene.getOutlineRenderer().render(subMesh, batch);
  28945. engine.setColorWrite(true);
  28946. }
  28947. // Overlay
  28948. if (this.renderOverlay) {
  28949. var currentMode = engine.getAlphaMode();
  28950. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28951. scene.getOutlineRenderer().render(subMesh, batch, true);
  28952. engine.setAlphaMode(currentMode);
  28953. }
  28954. this.onAfterRenderObservable.notifyObservers(this);
  28955. return this;
  28956. };
  28957. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  28958. if (isInstance && effectiveMaterial) {
  28959. effectiveMaterial.bindOnlyWorldMatrix(world);
  28960. }
  28961. };
  28962. /**
  28963. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  28964. */
  28965. Mesh.prototype.getEmittedParticleSystems = function () {
  28966. var results = new Array();
  28967. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28968. var particleSystem = this.getScene().particleSystems[index];
  28969. if (particleSystem.emitter === this) {
  28970. results.push(particleSystem);
  28971. }
  28972. }
  28973. return results;
  28974. };
  28975. /**
  28976. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  28977. */
  28978. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  28979. var results = new Array();
  28980. var descendants = this.getDescendants();
  28981. descendants.push(this);
  28982. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28983. var particleSystem = this.getScene().particleSystems[index];
  28984. var emitter = particleSystem.emitter;
  28985. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  28986. results.push(particleSystem);
  28987. }
  28988. }
  28989. return results;
  28990. };
  28991. Mesh.prototype._checkDelayState = function () {
  28992. var scene = this.getScene();
  28993. if (this._geometry) {
  28994. this._geometry.load(scene);
  28995. }
  28996. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  28997. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28998. this._queueLoad(scene);
  28999. }
  29000. return this;
  29001. };
  29002. Mesh.prototype._queueLoad = function (scene) {
  29003. var _this = this;
  29004. scene._addPendingData(this);
  29005. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  29006. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  29007. if (data instanceof ArrayBuffer) {
  29008. _this._delayLoadingFunction(data, _this);
  29009. }
  29010. else {
  29011. _this._delayLoadingFunction(JSON.parse(data), _this);
  29012. }
  29013. _this.instances.forEach(function (instance) {
  29014. instance._syncSubMeshes();
  29015. });
  29016. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29017. scene._removePendingData(_this);
  29018. }, function () { }, scene.database, getBinaryData);
  29019. return this;
  29020. };
  29021. /**
  29022. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  29023. */
  29024. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  29025. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  29026. return false;
  29027. }
  29028. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  29029. return false;
  29030. }
  29031. this._checkDelayState();
  29032. return true;
  29033. };
  29034. /**
  29035. * Sets the mesh material by the material or multiMaterial `id` property.
  29036. * The material `id` is a string identifying the material or the multiMaterial.
  29037. * This method returns the Mesh.
  29038. */
  29039. Mesh.prototype.setMaterialByID = function (id) {
  29040. var materials = this.getScene().materials;
  29041. var index;
  29042. for (index = materials.length - 1; index > -1; index--) {
  29043. if (materials[index].id === id) {
  29044. this.material = materials[index];
  29045. return this;
  29046. }
  29047. }
  29048. // Multi
  29049. var multiMaterials = this.getScene().multiMaterials;
  29050. for (index = multiMaterials.length - 1; index > -1; index--) {
  29051. if (multiMaterials[index].id === id) {
  29052. this.material = multiMaterials[index];
  29053. return this;
  29054. }
  29055. }
  29056. return this;
  29057. };
  29058. /**
  29059. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  29060. */
  29061. Mesh.prototype.getAnimatables = function () {
  29062. var results = new Array();
  29063. if (this.material) {
  29064. results.push(this.material);
  29065. }
  29066. if (this.skeleton) {
  29067. results.push(this.skeleton);
  29068. }
  29069. return results;
  29070. };
  29071. /**
  29072. * Modifies the mesh geometry according to the passed transformation matrix.
  29073. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  29074. * The mesh normals are modified accordingly the same transformation.
  29075. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  29076. * Note that, under the hood, this method sets a new VertexBuffer each call.
  29077. * Returns the Mesh.
  29078. */
  29079. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  29080. // Position
  29081. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29082. return this;
  29083. }
  29084. var submeshes = this.subMeshes.splice(0);
  29085. this._resetPointsArrayCache();
  29086. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29087. var temp = new Array();
  29088. var index;
  29089. for (index = 0; index < data.length; index += 3) {
  29090. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  29091. }
  29092. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  29093. // Normals
  29094. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29095. return this;
  29096. }
  29097. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29098. temp = [];
  29099. for (index = 0; index < data.length; index += 3) {
  29100. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  29101. }
  29102. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  29103. // flip faces?
  29104. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  29105. this.flipFaces();
  29106. }
  29107. // Restore submeshes
  29108. this.releaseSubMeshes();
  29109. this.subMeshes = submeshes;
  29110. return this;
  29111. };
  29112. /**
  29113. * Modifies the mesh geometry according to its own current World Matrix.
  29114. * The mesh World Matrix is then reset.
  29115. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  29116. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  29117. * Note that, under the hood, this method sets a new VertexBuffer each call.
  29118. * Returns the Mesh.
  29119. */
  29120. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  29121. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  29122. this.scaling.copyFromFloats(1, 1, 1);
  29123. this.position.copyFromFloats(0, 0, 0);
  29124. this.rotation.copyFromFloats(0, 0, 0);
  29125. //only if quaternion is already set
  29126. if (this.rotationQuaternion) {
  29127. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  29128. }
  29129. this._worldMatrix = BABYLON.Matrix.Identity();
  29130. return this;
  29131. };
  29132. Object.defineProperty(Mesh.prototype, "_positions", {
  29133. // Cache
  29134. get: function () {
  29135. if (this._geometry) {
  29136. return this._geometry._positions;
  29137. }
  29138. return null;
  29139. },
  29140. enumerable: true,
  29141. configurable: true
  29142. });
  29143. Mesh.prototype._resetPointsArrayCache = function () {
  29144. if (this._geometry) {
  29145. this._geometry._resetPointsArrayCache();
  29146. }
  29147. return this;
  29148. };
  29149. Mesh.prototype._generatePointsArray = function () {
  29150. if (this._geometry) {
  29151. return this._geometry._generatePointsArray();
  29152. }
  29153. return false;
  29154. };
  29155. /**
  29156. * Returns a new Mesh object generated from the current mesh properties.
  29157. * This method must not get confused with createInstance().
  29158. * The parameter `name` is a string, the name given to the new mesh.
  29159. * The optional parameter `newParent` can be any Node object (default `null`).
  29160. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  29161. * 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.
  29162. */
  29163. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  29164. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  29165. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  29166. };
  29167. /**
  29168. * Releases resources associated with this mesh.
  29169. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  29170. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  29171. */
  29172. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  29173. var _this = this;
  29174. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  29175. this.morphTargetManager = null;
  29176. if (this._geometry) {
  29177. this._geometry.releaseForMesh(this, true);
  29178. }
  29179. // Sources
  29180. var meshes = this.getScene().meshes;
  29181. meshes.forEach(function (abstractMesh) {
  29182. var mesh = abstractMesh;
  29183. if (mesh._source && mesh._source === _this) {
  29184. mesh._source = null;
  29185. }
  29186. });
  29187. this._source = null;
  29188. // Instances
  29189. if (this._instancesBuffer) {
  29190. this._instancesBuffer.dispose();
  29191. this._instancesBuffer = null;
  29192. }
  29193. while (this.instances.length) {
  29194. this.instances[0].dispose();
  29195. }
  29196. // Effect layers.
  29197. var effectLayers = this.getScene().effectLayers;
  29198. for (var i = 0; i < effectLayers.length; i++) {
  29199. var effectLayer = effectLayers[i];
  29200. if (effectLayer) {
  29201. effectLayer._disposeMesh(this);
  29202. }
  29203. }
  29204. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  29205. };
  29206. /**
  29207. * Modifies the mesh geometry according to a displacement map.
  29208. * 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.
  29209. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29210. * This method returns nothing.
  29211. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  29212. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29213. * 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.
  29214. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29215. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29216. *
  29217. * Returns the Mesh.
  29218. */
  29219. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  29220. var _this = this;
  29221. var scene = this.getScene();
  29222. var onload = function (img) {
  29223. // Getting height map data
  29224. var canvas = document.createElement("canvas");
  29225. var context = canvas.getContext("2d");
  29226. var heightMapWidth = img.width;
  29227. var heightMapHeight = img.height;
  29228. canvas.width = heightMapWidth;
  29229. canvas.height = heightMapHeight;
  29230. context.drawImage(img, 0, 0);
  29231. // Create VertexData from map data
  29232. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  29233. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  29234. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  29235. //execute success callback, if set
  29236. if (onSuccess) {
  29237. onSuccess(_this);
  29238. }
  29239. };
  29240. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  29241. return this;
  29242. };
  29243. /**
  29244. * Modifies the mesh geometry according to a displacementMap buffer.
  29245. * 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.
  29246. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29247. * This method returns nothing.
  29248. * 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.
  29249. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  29250. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29251. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29252. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29253. *
  29254. * Returns the Mesh.
  29255. */
  29256. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  29257. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  29258. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  29259. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29260. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  29261. return this;
  29262. }
  29263. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29264. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29265. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29266. var position = BABYLON.Vector3.Zero();
  29267. var normal = BABYLON.Vector3.Zero();
  29268. var uv = BABYLON.Vector2.Zero();
  29269. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  29270. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  29271. for (var index = 0; index < positions.length; index += 3) {
  29272. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  29273. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  29274. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  29275. // Compute height
  29276. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  29277. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  29278. var pos = (u + v * heightMapWidth) * 4;
  29279. var r = buffer[pos] / 255.0;
  29280. var g = buffer[pos + 1] / 255.0;
  29281. var b = buffer[pos + 2] / 255.0;
  29282. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  29283. normal.normalize();
  29284. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  29285. position = position.add(normal);
  29286. position.toArray(positions, index);
  29287. }
  29288. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  29289. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  29290. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  29291. return this;
  29292. };
  29293. /**
  29294. * Modify the mesh to get a flat shading rendering.
  29295. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  29296. * This method returns the Mesh.
  29297. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  29298. */
  29299. Mesh.prototype.convertToFlatShadedMesh = function () {
  29300. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  29301. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29302. var kinds = this.getVerticesDataKinds();
  29303. var vbs = {};
  29304. var data = {};
  29305. var newdata = {};
  29306. var updatableNormals = false;
  29307. var kindIndex;
  29308. var kind;
  29309. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29310. kind = kinds[kindIndex];
  29311. var vertexBuffer = this.getVertexBuffer(kind);
  29312. if (kind === BABYLON.VertexBuffer.NormalKind) {
  29313. updatableNormals = vertexBuffer.isUpdatable();
  29314. kinds.splice(kindIndex, 1);
  29315. kindIndex--;
  29316. continue;
  29317. }
  29318. vbs[kind] = vertexBuffer;
  29319. data[kind] = vbs[kind].getData();
  29320. newdata[kind] = [];
  29321. }
  29322. // Save previous submeshes
  29323. var previousSubmeshes = this.subMeshes.slice(0);
  29324. var indices = this.getIndices();
  29325. var totalIndices = this.getTotalIndices();
  29326. // Generating unique vertices per face
  29327. var index;
  29328. for (index = 0; index < totalIndices; index++) {
  29329. var vertexIndex = indices[index];
  29330. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29331. kind = kinds[kindIndex];
  29332. var stride = vbs[kind].getStrideSize();
  29333. for (var offset = 0; offset < stride; offset++) {
  29334. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29335. }
  29336. }
  29337. }
  29338. // Updating faces & normal
  29339. var normals = [];
  29340. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  29341. for (index = 0; index < totalIndices; index += 3) {
  29342. indices[index] = index;
  29343. indices[index + 1] = index + 1;
  29344. indices[index + 2] = index + 2;
  29345. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  29346. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  29347. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  29348. var p1p2 = p1.subtract(p2);
  29349. var p3p2 = p3.subtract(p2);
  29350. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  29351. // Store same normals for every vertex
  29352. for (var localIndex = 0; localIndex < 3; localIndex++) {
  29353. normals.push(normal.x);
  29354. normals.push(normal.y);
  29355. normals.push(normal.z);
  29356. }
  29357. }
  29358. this.setIndices(indices);
  29359. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  29360. // Updating vertex buffers
  29361. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29362. kind = kinds[kindIndex];
  29363. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29364. }
  29365. // Updating submeshes
  29366. this.releaseSubMeshes();
  29367. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29368. var previousOne = previousSubmeshes[submeshIndex];
  29369. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29370. }
  29371. this.synchronizeInstances();
  29372. return this;
  29373. };
  29374. /**
  29375. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  29376. * In other words, more vertices, no more indices and a single bigger VBO.
  29377. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  29378. * Returns the Mesh.
  29379. */
  29380. Mesh.prototype.convertToUnIndexedMesh = function () {
  29381. /// <summary>Remove indices by unfolding faces into buffers</summary>
  29382. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29383. var kinds = this.getVerticesDataKinds();
  29384. var vbs = {};
  29385. var data = {};
  29386. var newdata = {};
  29387. var kindIndex;
  29388. var kind;
  29389. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29390. kind = kinds[kindIndex];
  29391. var vertexBuffer = this.getVertexBuffer(kind);
  29392. vbs[kind] = vertexBuffer;
  29393. data[kind] = vbs[kind].getData();
  29394. newdata[kind] = [];
  29395. }
  29396. // Save previous submeshes
  29397. var previousSubmeshes = this.subMeshes.slice(0);
  29398. var indices = this.getIndices();
  29399. var totalIndices = this.getTotalIndices();
  29400. // Generating unique vertices per face
  29401. var index;
  29402. for (index = 0; index < totalIndices; index++) {
  29403. var vertexIndex = indices[index];
  29404. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29405. kind = kinds[kindIndex];
  29406. var stride = vbs[kind].getStrideSize();
  29407. for (var offset = 0; offset < stride; offset++) {
  29408. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29409. }
  29410. }
  29411. }
  29412. // Updating indices
  29413. for (index = 0; index < totalIndices; index += 3) {
  29414. indices[index] = index;
  29415. indices[index + 1] = index + 1;
  29416. indices[index + 2] = index + 2;
  29417. }
  29418. this.setIndices(indices);
  29419. // Updating vertex buffers
  29420. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29421. kind = kinds[kindIndex];
  29422. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29423. }
  29424. // Updating submeshes
  29425. this.releaseSubMeshes();
  29426. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29427. var previousOne = previousSubmeshes[submeshIndex];
  29428. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29429. }
  29430. this._unIndexed = true;
  29431. this.synchronizeInstances();
  29432. return this;
  29433. };
  29434. /**
  29435. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  29436. * This method returns the Mesh.
  29437. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  29438. */
  29439. Mesh.prototype.flipFaces = function (flipNormals) {
  29440. if (flipNormals === void 0) { flipNormals = false; }
  29441. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  29442. var i;
  29443. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  29444. for (i = 0; i < vertex_data.normals.length; i++) {
  29445. vertex_data.normals[i] *= -1;
  29446. }
  29447. }
  29448. if (vertex_data.indices) {
  29449. var temp;
  29450. for (i = 0; i < vertex_data.indices.length; i += 3) {
  29451. // reassign indices
  29452. temp = vertex_data.indices[i + 1];
  29453. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  29454. vertex_data.indices[i + 2] = temp;
  29455. }
  29456. }
  29457. vertex_data.applyToMesh(this);
  29458. return this;
  29459. };
  29460. // Instances
  29461. /**
  29462. * Creates a new InstancedMesh object from the mesh model.
  29463. * An instance shares the same properties and the same material than its model.
  29464. * Only these properties of each instance can then be set individually :
  29465. * - position
  29466. * - rotation
  29467. * - rotationQuaternion
  29468. * - setPivotMatrix
  29469. * - scaling
  29470. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  29471. * Warning : this method is not supported for Line mesh and LineSystem
  29472. */
  29473. Mesh.prototype.createInstance = function (name) {
  29474. return new BABYLON.InstancedMesh(name, this);
  29475. };
  29476. /**
  29477. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  29478. * After this call, all the mesh instances have the same submeshes than the current mesh.
  29479. * This method returns the Mesh.
  29480. */
  29481. Mesh.prototype.synchronizeInstances = function () {
  29482. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  29483. var instance = this.instances[instanceIndex];
  29484. instance._syncSubMeshes();
  29485. }
  29486. return this;
  29487. };
  29488. /**
  29489. * Simplify the mesh according to the given array of settings.
  29490. * Function will return immediately and will simplify async. It returns the Mesh.
  29491. * @param settings a collection of simplification settings.
  29492. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29493. * @param type the type of simplification to run.
  29494. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29495. */
  29496. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29497. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29498. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29499. this.getScene().simplificationQueue.addTask({
  29500. settings: settings,
  29501. parallelProcessing: parallelProcessing,
  29502. mesh: this,
  29503. simplificationType: simplificationType,
  29504. successCallback: successCallback
  29505. });
  29506. return this;
  29507. };
  29508. /**
  29509. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29510. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29511. * This should be used together with the simplification to avoid disappearing triangles.
  29512. * Returns the Mesh.
  29513. * @param successCallback an optional success callback to be called after the optimization finished.
  29514. */
  29515. Mesh.prototype.optimizeIndices = function (successCallback) {
  29516. var _this = this;
  29517. var indices = this.getIndices();
  29518. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29519. if (!positions || !indices) {
  29520. return this;
  29521. }
  29522. var vectorPositions = new Array();
  29523. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29524. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29525. }
  29526. var dupes = new Array();
  29527. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29528. var realPos = vectorPositions.length - 1 - iteration;
  29529. var testedPosition = vectorPositions[realPos];
  29530. for (var j = 0; j < realPos; ++j) {
  29531. var againstPosition = vectorPositions[j];
  29532. if (testedPosition.equals(againstPosition)) {
  29533. dupes[realPos] = j;
  29534. break;
  29535. }
  29536. }
  29537. }, function () {
  29538. for (var i = 0; i < indices.length; ++i) {
  29539. indices[i] = dupes[indices[i]] || indices[i];
  29540. }
  29541. //indices are now reordered
  29542. var originalSubMeshes = _this.subMeshes.slice(0);
  29543. _this.setIndices(indices);
  29544. _this.subMeshes = originalSubMeshes;
  29545. if (successCallback) {
  29546. successCallback(_this);
  29547. }
  29548. });
  29549. return this;
  29550. };
  29551. Mesh.prototype.serialize = function (serializationObject) {
  29552. serializationObject.name = this.name;
  29553. serializationObject.id = this.id;
  29554. serializationObject.type = this.getClassName();
  29555. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29556. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29557. }
  29558. serializationObject.position = this.position.asArray();
  29559. if (this.rotationQuaternion) {
  29560. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29561. }
  29562. else if (this.rotation) {
  29563. serializationObject.rotation = this.rotation.asArray();
  29564. }
  29565. serializationObject.scaling = this.scaling.asArray();
  29566. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29567. serializationObject.isEnabled = this.isEnabled(false);
  29568. serializationObject.isVisible = this.isVisible;
  29569. serializationObject.infiniteDistance = this.infiniteDistance;
  29570. serializationObject.pickable = this.isPickable;
  29571. serializationObject.receiveShadows = this.receiveShadows;
  29572. serializationObject.billboardMode = this.billboardMode;
  29573. serializationObject.visibility = this.visibility;
  29574. serializationObject.checkCollisions = this.checkCollisions;
  29575. serializationObject.isBlocker = this.isBlocker;
  29576. // Parent
  29577. if (this.parent) {
  29578. serializationObject.parentId = this.parent.id;
  29579. }
  29580. // Geometry
  29581. serializationObject.isUnIndexed = this.isUnIndexed;
  29582. var geometry = this._geometry;
  29583. if (geometry) {
  29584. var geometryId = geometry.id;
  29585. serializationObject.geometryId = geometryId;
  29586. // SubMeshes
  29587. serializationObject.subMeshes = [];
  29588. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29589. var subMesh = this.subMeshes[subIndex];
  29590. serializationObject.subMeshes.push({
  29591. materialIndex: subMesh.materialIndex,
  29592. verticesStart: subMesh.verticesStart,
  29593. verticesCount: subMesh.verticesCount,
  29594. indexStart: subMesh.indexStart,
  29595. indexCount: subMesh.indexCount
  29596. });
  29597. }
  29598. }
  29599. // Material
  29600. if (this.material) {
  29601. serializationObject.materialId = this.material.id;
  29602. }
  29603. else {
  29604. this.material = null;
  29605. }
  29606. // Morph targets
  29607. if (this.morphTargetManager) {
  29608. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29609. }
  29610. // Skeleton
  29611. if (this.skeleton) {
  29612. serializationObject.skeletonId = this.skeleton.id;
  29613. }
  29614. // Physics
  29615. //TODO implement correct serialization for physics impostors.
  29616. var impostor = this.getPhysicsImpostor();
  29617. if (impostor) {
  29618. serializationObject.physicsMass = impostor.getParam("mass");
  29619. serializationObject.physicsFriction = impostor.getParam("friction");
  29620. serializationObject.physicsRestitution = impostor.getParam("mass");
  29621. serializationObject.physicsImpostor = impostor.type;
  29622. }
  29623. // Metadata
  29624. if (this.metadata) {
  29625. serializationObject.metadata = this.metadata;
  29626. }
  29627. // Instances
  29628. serializationObject.instances = [];
  29629. for (var index = 0; index < this.instances.length; index++) {
  29630. var instance = this.instances[index];
  29631. var serializationInstance = {
  29632. name: instance.name,
  29633. id: instance.id,
  29634. position: instance.position.asArray(),
  29635. scaling: instance.scaling.asArray()
  29636. };
  29637. if (instance.rotationQuaternion) {
  29638. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29639. }
  29640. else if (instance.rotation) {
  29641. serializationInstance.rotation = instance.rotation.asArray();
  29642. }
  29643. serializationObject.instances.push(serializationInstance);
  29644. // Animations
  29645. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29646. serializationInstance.ranges = instance.serializeAnimationRanges();
  29647. }
  29648. //
  29649. // Animations
  29650. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29651. serializationObject.ranges = this.serializeAnimationRanges();
  29652. // Layer mask
  29653. serializationObject.layerMask = this.layerMask;
  29654. // Alpha
  29655. serializationObject.alphaIndex = this.alphaIndex;
  29656. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29657. // Overlay
  29658. serializationObject.overlayAlpha = this.overlayAlpha;
  29659. serializationObject.overlayColor = this.overlayColor.asArray();
  29660. serializationObject.renderOverlay = this.renderOverlay;
  29661. // Fog
  29662. serializationObject.applyFog = this.applyFog;
  29663. // Action Manager
  29664. if (this.actionManager) {
  29665. serializationObject.actions = this.actionManager.serialize(this.name);
  29666. }
  29667. };
  29668. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29669. if (!this.geometry) {
  29670. return;
  29671. }
  29672. this._markSubMeshesAsAttributesDirty();
  29673. var morphTargetManager = this._morphTargetManager;
  29674. if (morphTargetManager && morphTargetManager.vertexCount) {
  29675. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29676. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29677. this.morphTargetManager = null;
  29678. return;
  29679. }
  29680. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29681. var morphTarget = morphTargetManager.getActiveTarget(index);
  29682. var positions = morphTarget.getPositions();
  29683. if (!positions) {
  29684. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29685. return;
  29686. }
  29687. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29688. var normals = morphTarget.getNormals();
  29689. if (normals) {
  29690. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29691. }
  29692. var tangents = morphTarget.getTangents();
  29693. if (tangents) {
  29694. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29695. }
  29696. }
  29697. }
  29698. else {
  29699. var index = 0;
  29700. // Positions
  29701. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29702. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29703. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29704. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29705. }
  29706. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29707. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29708. }
  29709. index++;
  29710. }
  29711. }
  29712. };
  29713. // Statics
  29714. /**
  29715. * Returns a new Mesh object parsed from the source provided.
  29716. * The parameter `parsedMesh` is the source.
  29717. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29718. */
  29719. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29720. var mesh;
  29721. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29722. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29723. }
  29724. else {
  29725. mesh = new Mesh(parsedMesh.name, scene);
  29726. }
  29727. mesh.id = parsedMesh.id;
  29728. if (BABYLON.Tags) {
  29729. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29730. }
  29731. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29732. if (parsedMesh.metadata !== undefined) {
  29733. mesh.metadata = parsedMesh.metadata;
  29734. }
  29735. if (parsedMesh.rotationQuaternion) {
  29736. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29737. }
  29738. else if (parsedMesh.rotation) {
  29739. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29740. }
  29741. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29742. if (parsedMesh.localMatrix) {
  29743. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29744. }
  29745. else if (parsedMesh.pivotMatrix) {
  29746. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29747. }
  29748. mesh.setEnabled(parsedMesh.isEnabled);
  29749. mesh.isVisible = parsedMesh.isVisible;
  29750. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29751. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29752. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29753. if (parsedMesh.applyFog !== undefined) {
  29754. mesh.applyFog = parsedMesh.applyFog;
  29755. }
  29756. if (parsedMesh.pickable !== undefined) {
  29757. mesh.isPickable = parsedMesh.pickable;
  29758. }
  29759. if (parsedMesh.alphaIndex !== undefined) {
  29760. mesh.alphaIndex = parsedMesh.alphaIndex;
  29761. }
  29762. mesh.receiveShadows = parsedMesh.receiveShadows;
  29763. mesh.billboardMode = parsedMesh.billboardMode;
  29764. if (parsedMesh.visibility !== undefined) {
  29765. mesh.visibility = parsedMesh.visibility;
  29766. }
  29767. mesh.checkCollisions = parsedMesh.checkCollisions;
  29768. if (parsedMesh.isBlocker !== undefined) {
  29769. mesh.isBlocker = parsedMesh.isBlocker;
  29770. }
  29771. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29772. // freezeWorldMatrix
  29773. if (parsedMesh.freezeWorldMatrix) {
  29774. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29775. }
  29776. // Parent
  29777. if (parsedMesh.parentId) {
  29778. mesh._waitingParentId = parsedMesh.parentId;
  29779. }
  29780. // Actions
  29781. if (parsedMesh.actions !== undefined) {
  29782. mesh._waitingActions = parsedMesh.actions;
  29783. }
  29784. // Overlay
  29785. if (parsedMesh.overlayAlpha !== undefined) {
  29786. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29787. }
  29788. if (parsedMesh.overlayColor !== undefined) {
  29789. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29790. }
  29791. if (parsedMesh.renderOverlay !== undefined) {
  29792. mesh.renderOverlay = parsedMesh.renderOverlay;
  29793. }
  29794. // Geometry
  29795. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29796. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29797. if (parsedMesh.delayLoadingFile) {
  29798. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29799. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29800. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29801. if (parsedMesh._binaryInfo) {
  29802. mesh._binaryInfo = parsedMesh._binaryInfo;
  29803. }
  29804. mesh._delayInfo = [];
  29805. if (parsedMesh.hasUVs) {
  29806. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29807. }
  29808. if (parsedMesh.hasUVs2) {
  29809. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29810. }
  29811. if (parsedMesh.hasUVs3) {
  29812. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29813. }
  29814. if (parsedMesh.hasUVs4) {
  29815. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29816. }
  29817. if (parsedMesh.hasUVs5) {
  29818. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29819. }
  29820. if (parsedMesh.hasUVs6) {
  29821. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29822. }
  29823. if (parsedMesh.hasColors) {
  29824. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29825. }
  29826. if (parsedMesh.hasMatricesIndices) {
  29827. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29828. }
  29829. if (parsedMesh.hasMatricesWeights) {
  29830. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29831. }
  29832. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29833. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29834. mesh._checkDelayState();
  29835. }
  29836. }
  29837. else {
  29838. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29839. }
  29840. // Material
  29841. if (parsedMesh.materialId) {
  29842. mesh.setMaterialByID(parsedMesh.materialId);
  29843. }
  29844. else {
  29845. mesh.material = null;
  29846. }
  29847. // Morph targets
  29848. if (parsedMesh.morphTargetManagerId > -1) {
  29849. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29850. }
  29851. // Skeleton
  29852. if (parsedMesh.skeletonId > -1) {
  29853. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29854. if (parsedMesh.numBoneInfluencers) {
  29855. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29856. }
  29857. }
  29858. // Animations
  29859. if (parsedMesh.animations) {
  29860. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29861. var parsedAnimation = parsedMesh.animations[animationIndex];
  29862. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29863. }
  29864. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29865. }
  29866. if (parsedMesh.autoAnimate) {
  29867. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29868. }
  29869. // Layer Mask
  29870. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29871. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29872. }
  29873. else {
  29874. mesh.layerMask = 0x0FFFFFFF;
  29875. }
  29876. // Physics
  29877. if (parsedMesh.physicsImpostor) {
  29878. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29879. mass: parsedMesh.physicsMass,
  29880. friction: parsedMesh.physicsFriction,
  29881. restitution: parsedMesh.physicsRestitution
  29882. }, scene);
  29883. }
  29884. // Instances
  29885. if (parsedMesh.instances) {
  29886. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29887. var parsedInstance = parsedMesh.instances[index];
  29888. var instance = mesh.createInstance(parsedInstance.name);
  29889. if (parsedInstance.id) {
  29890. instance.id = parsedInstance.id;
  29891. }
  29892. if (BABYLON.Tags) {
  29893. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  29894. }
  29895. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  29896. if (parsedInstance.parentId) {
  29897. instance._waitingParentId = parsedInstance.parentId;
  29898. }
  29899. if (parsedInstance.rotationQuaternion) {
  29900. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  29901. }
  29902. else if (parsedInstance.rotation) {
  29903. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  29904. }
  29905. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  29906. instance.checkCollisions = mesh.checkCollisions;
  29907. if (parsedMesh.animations) {
  29908. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29909. parsedAnimation = parsedMesh.animations[animationIndex];
  29910. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29911. }
  29912. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  29913. }
  29914. }
  29915. }
  29916. return mesh;
  29917. };
  29918. /**
  29919. * Creates a ribbon mesh.
  29920. * Please consider using the same method from the MeshBuilder class instead.
  29921. * 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.
  29922. *
  29923. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  29924. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  29925. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  29926. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  29927. * 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.
  29928. * 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.
  29929. * 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
  29930. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29931. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29932. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29933. */
  29934. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  29935. if (closeArray === void 0) { closeArray = false; }
  29936. if (updatable === void 0) { updatable = false; }
  29937. return BABYLON.MeshBuilder.CreateRibbon(name, {
  29938. pathArray: pathArray,
  29939. closeArray: closeArray,
  29940. closePath: closePath,
  29941. offset: offset,
  29942. updatable: updatable,
  29943. sideOrientation: sideOrientation,
  29944. instance: instance
  29945. }, scene);
  29946. };
  29947. /**
  29948. * Creates a plane polygonal mesh. By default, this is a disc.
  29949. * Please consider using the same method from the MeshBuilder class instead.
  29950. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  29951. * 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.
  29952. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29953. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29954. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29955. */
  29956. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  29957. if (scene === void 0) { scene = null; }
  29958. var options = {
  29959. radius: radius,
  29960. tessellation: tessellation,
  29961. sideOrientation: sideOrientation,
  29962. updatable: updatable
  29963. };
  29964. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  29965. };
  29966. /**
  29967. * Creates a box mesh.
  29968. * Please consider using the same method from the MeshBuilder class instead.
  29969. * The parameter `size` sets the size (float) of each box side (default 1).
  29970. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29971. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29972. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29973. */
  29974. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  29975. if (scene === void 0) { scene = null; }
  29976. var options = {
  29977. size: size,
  29978. sideOrientation: sideOrientation,
  29979. updatable: updatable
  29980. };
  29981. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  29982. };
  29983. /**
  29984. * Creates a sphere mesh.
  29985. * Please consider using the same method from the MeshBuilder class instead.
  29986. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  29987. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  29988. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29989. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29990. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29991. */
  29992. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  29993. var options = {
  29994. segments: segments,
  29995. diameterX: diameter,
  29996. diameterY: diameter,
  29997. diameterZ: diameter,
  29998. sideOrientation: sideOrientation,
  29999. updatable: updatable
  30000. };
  30001. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  30002. };
  30003. /**
  30004. * Creates a cylinder or a cone mesh.
  30005. * Please consider using the same method from the MeshBuilder class instead.
  30006. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  30007. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  30008. * 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.
  30009. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  30010. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  30011. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30012. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30013. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30014. */
  30015. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  30016. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  30017. if (scene !== undefined) {
  30018. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  30019. updatable = scene;
  30020. }
  30021. scene = subdivisions;
  30022. subdivisions = 1;
  30023. }
  30024. var options = {
  30025. height: height,
  30026. diameterTop: diameterTop,
  30027. diameterBottom: diameterBottom,
  30028. tessellation: tessellation,
  30029. subdivisions: subdivisions,
  30030. sideOrientation: sideOrientation,
  30031. updatable: updatable
  30032. };
  30033. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  30034. };
  30035. // Torus (Code from SharpDX.org)
  30036. /**
  30037. * Creates a torus mesh.
  30038. * Please consider using the same method from the MeshBuilder class instead.
  30039. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  30040. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  30041. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  30042. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30043. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30044. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30045. */
  30046. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  30047. var options = {
  30048. diameter: diameter,
  30049. thickness: thickness,
  30050. tessellation: tessellation,
  30051. sideOrientation: sideOrientation,
  30052. updatable: updatable
  30053. };
  30054. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  30055. };
  30056. /**
  30057. * Creates a torus knot mesh.
  30058. * Please consider using the same method from the MeshBuilder class instead.
  30059. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  30060. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  30061. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  30062. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  30063. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30064. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30065. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30066. */
  30067. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  30068. var options = {
  30069. radius: radius,
  30070. tube: tube,
  30071. radialSegments: radialSegments,
  30072. tubularSegments: tubularSegments,
  30073. p: p,
  30074. q: q,
  30075. sideOrientation: sideOrientation,
  30076. updatable: updatable
  30077. };
  30078. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  30079. };
  30080. /**
  30081. * Creates a line mesh.
  30082. * Please consider using the same method from the MeshBuilder class instead.
  30083. * 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.
  30084. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  30085. * The parameter `points` is an array successive Vector3.
  30086. * 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
  30087. * When updating an instance, remember that only point positions can change, not the number of points.
  30088. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30089. */
  30090. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  30091. if (scene === void 0) { scene = null; }
  30092. if (updatable === void 0) { updatable = false; }
  30093. if (instance === void 0) { instance = null; }
  30094. var options = {
  30095. points: points,
  30096. updatable: updatable,
  30097. instance: instance
  30098. };
  30099. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  30100. };
  30101. /**
  30102. * Creates a dashed line mesh.
  30103. * Please consider using the same method from the MeshBuilder class instead.
  30104. * 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.
  30105. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  30106. * The parameter `points` is an array successive Vector3.
  30107. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  30108. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  30109. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  30110. * 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
  30111. * When updating an instance, remember that only point positions can change, not the number of points.
  30112. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30113. */
  30114. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  30115. if (scene === void 0) { scene = null; }
  30116. var options = {
  30117. points: points,
  30118. dashSize: dashSize,
  30119. gapSize: gapSize,
  30120. dashNb: dashNb,
  30121. updatable: updatable,
  30122. instance: instance
  30123. };
  30124. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  30125. };
  30126. /**
  30127. * Creates a polygon mesh.
  30128. * Please consider using the same method from the MeshBuilder class instead.
  30129. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  30130. * 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.
  30131. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30132. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30133. * Remember you can only change the shape positions, not their number when updating a polygon.
  30134. */
  30135. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  30136. var options = {
  30137. shape: shape,
  30138. holes: holes,
  30139. updatable: updatable,
  30140. sideOrientation: sideOrientation
  30141. };
  30142. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  30143. };
  30144. /**
  30145. * Creates an extruded polygon mesh, with depth in the Y direction.
  30146. * Please consider using the same method from the MeshBuilder class instead.
  30147. */
  30148. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  30149. var options = {
  30150. shape: shape,
  30151. holes: holes,
  30152. depth: depth,
  30153. updatable: updatable,
  30154. sideOrientation: sideOrientation
  30155. };
  30156. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  30157. };
  30158. /**
  30159. * Creates an extruded shape mesh.
  30160. * 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.
  30161. * Please consider using the same method from the MeshBuilder class instead.
  30162. *
  30163. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30164. * 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
  30165. * extruded along the Z axis.
  30166. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30167. * 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.
  30168. * The parameter `scale` (float, default 1) is the value to scale the shape.
  30169. * 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
  30170. * 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
  30171. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30172. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30173. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30174. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30175. */
  30176. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  30177. if (scene === void 0) { scene = null; }
  30178. var options = {
  30179. shape: shape,
  30180. path: path,
  30181. scale: scale,
  30182. rotation: rotation,
  30183. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30184. sideOrientation: sideOrientation,
  30185. instance: instance,
  30186. updatable: updatable
  30187. };
  30188. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  30189. };
  30190. /**
  30191. * Creates an custom extruded shape mesh.
  30192. * 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.
  30193. * Please consider using the same method from the MeshBuilder class instead.
  30194. *
  30195. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30196. * 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
  30197. * extruded along the Z axis.
  30198. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30199. * 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
  30200. * and the distance of this point from the begining of the path :
  30201. * ```javascript
  30202. * var rotationFunction = function(i, distance) {
  30203. * // do things
  30204. * return rotationValue; }
  30205. * ```
  30206. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  30207. * 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
  30208. * and the distance of this point from the begining of the path :
  30209. * ```javascript
  30210. * var scaleFunction = function(i, distance) {
  30211. * // do things
  30212. * return scaleValue;}
  30213. * ```
  30214. * It must returns a float value that will be the scale value applied to the shape on each path point.
  30215. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  30216. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  30217. * 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
  30218. * 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
  30219. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30220. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30221. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30222. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30223. */
  30224. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  30225. var options = {
  30226. shape: shape,
  30227. path: path,
  30228. scaleFunction: scaleFunction,
  30229. rotationFunction: rotationFunction,
  30230. ribbonCloseArray: ribbonCloseArray,
  30231. ribbonClosePath: ribbonClosePath,
  30232. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30233. sideOrientation: sideOrientation,
  30234. instance: instance,
  30235. updatable: updatable
  30236. };
  30237. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  30238. };
  30239. /**
  30240. * Creates lathe mesh.
  30241. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  30242. * Please consider using the same method from the MeshBuilder class instead.
  30243. * 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
  30244. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  30245. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  30246. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  30247. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30248. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30249. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30250. */
  30251. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  30252. var options = {
  30253. shape: shape,
  30254. radius: radius,
  30255. tessellation: tessellation,
  30256. sideOrientation: sideOrientation,
  30257. updatable: updatable
  30258. };
  30259. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  30260. };
  30261. /**
  30262. * Creates a plane mesh.
  30263. * Please consider using the same method from the MeshBuilder class instead.
  30264. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  30265. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30266. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30267. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30268. */
  30269. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  30270. var options = {
  30271. size: size,
  30272. width: size,
  30273. height: size,
  30274. sideOrientation: sideOrientation,
  30275. updatable: updatable
  30276. };
  30277. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  30278. };
  30279. /**
  30280. * Creates a ground mesh.
  30281. * Please consider using the same method from the MeshBuilder class instead.
  30282. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  30283. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  30284. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30285. */
  30286. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  30287. var options = {
  30288. width: width,
  30289. height: height,
  30290. subdivisions: subdivisions,
  30291. updatable: updatable
  30292. };
  30293. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  30294. };
  30295. /**
  30296. * Creates a tiled ground mesh.
  30297. * Please consider using the same method from the MeshBuilder class instead.
  30298. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  30299. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  30300. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  30301. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  30302. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  30303. * numbers of subdivisions on the ground width and height of each tile.
  30304. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30305. */
  30306. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  30307. var options = {
  30308. xmin: xmin,
  30309. zmin: zmin,
  30310. xmax: xmax,
  30311. zmax: zmax,
  30312. subdivisions: subdivisions,
  30313. precision: precision,
  30314. updatable: updatable
  30315. };
  30316. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  30317. };
  30318. /**
  30319. * Creates a ground mesh from a height map.
  30320. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  30321. * Please consider using the same method from the MeshBuilder class instead.
  30322. * The parameter `url` sets the URL of the height map image resource.
  30323. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  30324. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  30325. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  30326. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  30327. * 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).
  30328. * This function is passed the newly built mesh :
  30329. * ```javascript
  30330. * function(mesh) { // do things
  30331. * return; }
  30332. * ```
  30333. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30334. */
  30335. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  30336. var options = {
  30337. width: width,
  30338. height: height,
  30339. subdivisions: subdivisions,
  30340. minHeight: minHeight,
  30341. maxHeight: maxHeight,
  30342. updatable: updatable,
  30343. onReady: onReady
  30344. };
  30345. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  30346. };
  30347. /**
  30348. * Creates a tube mesh.
  30349. * 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.
  30350. * Please consider using the same method from the MeshBuilder class instead.
  30351. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  30352. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  30353. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  30354. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  30355. * 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.
  30356. * It must return a radius value (positive float) :
  30357. * ```javascript
  30358. * var radiusFunction = function(i, distance) {
  30359. * // do things
  30360. * return radius; }
  30361. * ```
  30362. * 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
  30363. * 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
  30364. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30365. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30366. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30367. */
  30368. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  30369. var options = {
  30370. path: path,
  30371. radius: radius,
  30372. tessellation: tessellation,
  30373. radiusFunction: radiusFunction,
  30374. arc: 1,
  30375. cap: cap,
  30376. updatable: updatable,
  30377. sideOrientation: sideOrientation,
  30378. instance: instance
  30379. };
  30380. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  30381. };
  30382. /**
  30383. * Creates a polyhedron mesh.
  30384. * Please consider using the same method from the MeshBuilder class instead.
  30385. * 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
  30386. * to choose the wanted type.
  30387. * The parameter `size` (positive float, default 1) sets the polygon size.
  30388. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  30389. * 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`.
  30390. * 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
  30391. * 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)`).
  30392. * 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
  30393. * 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.
  30394. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30395. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30396. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30397. */
  30398. Mesh.CreatePolyhedron = function (name, options, scene) {
  30399. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  30400. };
  30401. /**
  30402. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  30403. * Please consider using the same method from the MeshBuilder class instead.
  30404. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  30405. * 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`).
  30406. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  30407. * 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.
  30408. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30409. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30410. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30411. */
  30412. Mesh.CreateIcoSphere = function (name, options, scene) {
  30413. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  30414. };
  30415. /**
  30416. * Creates a decal mesh.
  30417. * Please consider using the same method from the MeshBuilder class instead.
  30418. * 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.
  30419. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  30420. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  30421. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  30422. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  30423. */
  30424. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  30425. var options = {
  30426. position: position,
  30427. normal: normal,
  30428. size: size,
  30429. angle: angle
  30430. };
  30431. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  30432. };
  30433. // Skeletons
  30434. /**
  30435. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30436. */
  30437. Mesh.prototype.setPositionsForCPUSkinning = function () {
  30438. if (!this._sourcePositions) {
  30439. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30440. if (!source) {
  30441. return this._sourcePositions;
  30442. }
  30443. this._sourcePositions = new Float32Array(source);
  30444. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30445. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  30446. }
  30447. }
  30448. return this._sourcePositions;
  30449. };
  30450. /**
  30451. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30452. */
  30453. Mesh.prototype.setNormalsForCPUSkinning = function () {
  30454. if (!this._sourceNormals) {
  30455. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30456. if (!source) {
  30457. return this._sourceNormals;
  30458. }
  30459. this._sourceNormals = new Float32Array(source);
  30460. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30461. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  30462. }
  30463. }
  30464. return this._sourceNormals;
  30465. };
  30466. /**
  30467. * Updates the vertex buffer by applying transformation from the bones.
  30468. * Returns the Mesh.
  30469. *
  30470. * @param {skeleton} skeleton to apply
  30471. */
  30472. Mesh.prototype.applySkeleton = function (skeleton) {
  30473. if (!this.geometry) {
  30474. return this;
  30475. }
  30476. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  30477. return this;
  30478. }
  30479. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  30480. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30481. return this;
  30482. }
  30483. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30484. return this;
  30485. }
  30486. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30487. return this;
  30488. }
  30489. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30490. return this;
  30491. }
  30492. if (!this._sourcePositions) {
  30493. var submeshes = this.subMeshes.slice();
  30494. this.setPositionsForCPUSkinning();
  30495. this.subMeshes = submeshes;
  30496. }
  30497. if (!this._sourceNormals) {
  30498. this.setNormalsForCPUSkinning();
  30499. }
  30500. // positionsData checks for not being Float32Array will only pass at most once
  30501. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30502. if (!positionsData) {
  30503. return this;
  30504. }
  30505. if (!(positionsData instanceof Float32Array)) {
  30506. positionsData = new Float32Array(positionsData);
  30507. }
  30508. // normalsData checks for not being Float32Array will only pass at most once
  30509. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30510. if (!normalsData) {
  30511. return this;
  30512. }
  30513. if (!(normalsData instanceof Float32Array)) {
  30514. normalsData = new Float32Array(normalsData);
  30515. }
  30516. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30517. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30518. if (!matricesWeightsData || !matricesIndicesData) {
  30519. return this;
  30520. }
  30521. var needExtras = this.numBoneInfluencers > 4;
  30522. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30523. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30524. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30525. var tempVector3 = BABYLON.Vector3.Zero();
  30526. var finalMatrix = new BABYLON.Matrix();
  30527. var tempMatrix = new BABYLON.Matrix();
  30528. var matWeightIdx = 0;
  30529. var inf;
  30530. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30531. var weight;
  30532. for (inf = 0; inf < 4; inf++) {
  30533. weight = matricesWeightsData[matWeightIdx + inf];
  30534. if (weight > 0) {
  30535. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30536. finalMatrix.addToSelf(tempMatrix);
  30537. }
  30538. else
  30539. break;
  30540. }
  30541. if (needExtras) {
  30542. for (inf = 0; inf < 4; inf++) {
  30543. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30544. if (weight > 0) {
  30545. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30546. finalMatrix.addToSelf(tempMatrix);
  30547. }
  30548. else
  30549. break;
  30550. }
  30551. }
  30552. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30553. tempVector3.toArray(positionsData, index);
  30554. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30555. tempVector3.toArray(normalsData, index);
  30556. finalMatrix.reset();
  30557. }
  30558. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30559. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30560. return this;
  30561. };
  30562. // Tools
  30563. /**
  30564. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30565. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30566. */
  30567. Mesh.MinMax = function (meshes) {
  30568. var minVector = null;
  30569. var maxVector = null;
  30570. meshes.forEach(function (mesh, index, array) {
  30571. var boundingInfo = mesh.getBoundingInfo();
  30572. var boundingBox = boundingInfo.boundingBox;
  30573. if (!minVector || !maxVector) {
  30574. minVector = boundingBox.minimumWorld;
  30575. maxVector = boundingBox.maximumWorld;
  30576. }
  30577. else {
  30578. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30579. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30580. }
  30581. });
  30582. if (!minVector || !maxVector) {
  30583. return {
  30584. min: BABYLON.Vector3.Zero(),
  30585. max: BABYLON.Vector3.Zero()
  30586. };
  30587. }
  30588. return {
  30589. min: minVector,
  30590. max: maxVector
  30591. };
  30592. };
  30593. /**
  30594. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30595. */
  30596. Mesh.Center = function (meshesOrMinMaxVector) {
  30597. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30598. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30599. };
  30600. /**
  30601. * Merge the array of meshes into a single mesh for performance reasons.
  30602. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30603. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30604. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30605. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30606. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30607. */
  30608. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30609. if (disposeSource === void 0) { disposeSource = true; }
  30610. var index;
  30611. if (!allow32BitsIndices) {
  30612. var totalVertices = 0;
  30613. // Counting vertices
  30614. for (index = 0; index < meshes.length; index++) {
  30615. if (meshes[index]) {
  30616. totalVertices += meshes[index].getTotalVertices();
  30617. if (totalVertices > 65536) {
  30618. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30619. return null;
  30620. }
  30621. }
  30622. }
  30623. }
  30624. // Merge
  30625. var vertexData = null;
  30626. var otherVertexData;
  30627. var indiceArray = new Array();
  30628. var source = null;
  30629. for (index = 0; index < meshes.length; index++) {
  30630. if (meshes[index]) {
  30631. meshes[index].computeWorldMatrix(true);
  30632. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30633. otherVertexData.transform(meshes[index].getWorldMatrix());
  30634. if (vertexData) {
  30635. vertexData.merge(otherVertexData);
  30636. }
  30637. else {
  30638. vertexData = otherVertexData;
  30639. source = meshes[index];
  30640. }
  30641. if (subdivideWithSubMeshes) {
  30642. indiceArray.push(meshes[index].getTotalIndices());
  30643. }
  30644. }
  30645. }
  30646. source = source;
  30647. if (!meshSubclass) {
  30648. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30649. }
  30650. vertexData.applyToMesh(meshSubclass);
  30651. // Setting properties
  30652. meshSubclass.material = source.material;
  30653. meshSubclass.checkCollisions = source.checkCollisions;
  30654. // Cleaning
  30655. if (disposeSource) {
  30656. for (index = 0; index < meshes.length; index++) {
  30657. if (meshes[index]) {
  30658. meshes[index].dispose();
  30659. }
  30660. }
  30661. }
  30662. // Subdivide
  30663. if (subdivideWithSubMeshes) {
  30664. //-- Suppresions du submesh global
  30665. meshSubclass.releaseSubMeshes();
  30666. index = 0;
  30667. var offset = 0;
  30668. //-- aplique la subdivision en fonction du tableau d'indices
  30669. while (index < indiceArray.length) {
  30670. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30671. offset += indiceArray[index];
  30672. index++;
  30673. }
  30674. }
  30675. return meshSubclass;
  30676. };
  30677. // Consts
  30678. Mesh._FRONTSIDE = 0;
  30679. Mesh._BACKSIDE = 1;
  30680. Mesh._DOUBLESIDE = 2;
  30681. Mesh._DEFAULTSIDE = 0;
  30682. Mesh._NO_CAP = 0;
  30683. Mesh._CAP_START = 1;
  30684. Mesh._CAP_END = 2;
  30685. Mesh._CAP_ALL = 3;
  30686. return Mesh;
  30687. }(BABYLON.AbstractMesh));
  30688. BABYLON.Mesh = Mesh;
  30689. })(BABYLON || (BABYLON = {}));
  30690. //# sourceMappingURL=babylon.mesh.js.map
  30691. var BABYLON;
  30692. (function (BABYLON) {
  30693. var BaseSubMesh = /** @class */ (function () {
  30694. function BaseSubMesh() {
  30695. }
  30696. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30697. get: function () {
  30698. return this._materialEffect;
  30699. },
  30700. enumerable: true,
  30701. configurable: true
  30702. });
  30703. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30704. if (defines === void 0) { defines = null; }
  30705. if (this._materialEffect === effect) {
  30706. if (!effect) {
  30707. this._materialDefines = null;
  30708. }
  30709. return;
  30710. }
  30711. this._materialDefines = defines;
  30712. this._materialEffect = effect;
  30713. };
  30714. return BaseSubMesh;
  30715. }());
  30716. BABYLON.BaseSubMesh = BaseSubMesh;
  30717. var SubMesh = /** @class */ (function (_super) {
  30718. __extends(SubMesh, _super);
  30719. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30720. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30721. var _this = _super.call(this) || this;
  30722. _this.materialIndex = materialIndex;
  30723. _this.verticesStart = verticesStart;
  30724. _this.verticesCount = verticesCount;
  30725. _this.indexStart = indexStart;
  30726. _this.indexCount = indexCount;
  30727. _this._renderId = 0;
  30728. _this._mesh = mesh;
  30729. _this._renderingMesh = renderingMesh || mesh;
  30730. mesh.subMeshes.push(_this);
  30731. _this._trianglePlanes = [];
  30732. _this._id = mesh.subMeshes.length - 1;
  30733. if (createBoundingBox) {
  30734. _this.refreshBoundingInfo();
  30735. mesh.computeWorldMatrix(true);
  30736. }
  30737. return _this;
  30738. }
  30739. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30740. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30741. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30742. };
  30743. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30744. get: function () {
  30745. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30746. },
  30747. enumerable: true,
  30748. configurable: true
  30749. });
  30750. /**
  30751. * Returns the submesh BoudingInfo object.
  30752. */
  30753. SubMesh.prototype.getBoundingInfo = function () {
  30754. if (this.IsGlobal) {
  30755. return this._mesh.getBoundingInfo();
  30756. }
  30757. return this._boundingInfo;
  30758. };
  30759. /**
  30760. * Sets the submesh BoundingInfo.
  30761. * Return the SubMesh.
  30762. */
  30763. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30764. this._boundingInfo = boundingInfo;
  30765. return this;
  30766. };
  30767. /**
  30768. * Returns the mesh of the current submesh.
  30769. */
  30770. SubMesh.prototype.getMesh = function () {
  30771. return this._mesh;
  30772. };
  30773. /**
  30774. * Returns the rendering mesh of the submesh.
  30775. */
  30776. SubMesh.prototype.getRenderingMesh = function () {
  30777. return this._renderingMesh;
  30778. };
  30779. /**
  30780. * Returns the submesh material.
  30781. */
  30782. SubMesh.prototype.getMaterial = function () {
  30783. var rootMaterial = this._renderingMesh.material;
  30784. if (rootMaterial === null || rootMaterial === undefined) {
  30785. return this._mesh.getScene().defaultMaterial;
  30786. }
  30787. else if (rootMaterial.getSubMaterial) {
  30788. var multiMaterial = rootMaterial;
  30789. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30790. if (this._currentMaterial !== effectiveMaterial) {
  30791. this._currentMaterial = effectiveMaterial;
  30792. this._materialDefines = null;
  30793. }
  30794. return effectiveMaterial;
  30795. }
  30796. return rootMaterial;
  30797. };
  30798. // Methods
  30799. /**
  30800. * Sets a new updated BoundingInfo object to the submesh.
  30801. * Returns the SubMesh.
  30802. */
  30803. SubMesh.prototype.refreshBoundingInfo = function () {
  30804. this._lastColliderWorldVertices = null;
  30805. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30806. return this;
  30807. }
  30808. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30809. if (!data) {
  30810. this._boundingInfo = this._mesh.getBoundingInfo();
  30811. return this;
  30812. }
  30813. var indices = this._renderingMesh.getIndices();
  30814. var extend;
  30815. //is this the only submesh?
  30816. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30817. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30818. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30819. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30820. }
  30821. else {
  30822. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30823. }
  30824. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30825. return this;
  30826. };
  30827. SubMesh.prototype._checkCollision = function (collider) {
  30828. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30829. return boundingInfo._checkCollision(collider);
  30830. };
  30831. /**
  30832. * Updates the submesh BoundingInfo.
  30833. * Returns the Submesh.
  30834. */
  30835. SubMesh.prototype.updateBoundingInfo = function (world) {
  30836. var boundingInfo = this.getBoundingInfo();
  30837. if (!boundingInfo) {
  30838. this.refreshBoundingInfo();
  30839. boundingInfo = this.getBoundingInfo();
  30840. }
  30841. boundingInfo.update(world);
  30842. return this;
  30843. };
  30844. /**
  30845. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30846. * Boolean returned.
  30847. */
  30848. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30849. var boundingInfo = this.getBoundingInfo();
  30850. if (!boundingInfo) {
  30851. return false;
  30852. }
  30853. return boundingInfo.isInFrustum(frustumPlanes);
  30854. };
  30855. /**
  30856. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30857. * Boolean returned.
  30858. */
  30859. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30860. var boundingInfo = this.getBoundingInfo();
  30861. if (!boundingInfo) {
  30862. return false;
  30863. }
  30864. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30865. };
  30866. /**
  30867. * Renders the submesh.
  30868. * Returns it.
  30869. */
  30870. SubMesh.prototype.render = function (enableAlphaMode) {
  30871. this._renderingMesh.render(this, enableAlphaMode);
  30872. return this;
  30873. };
  30874. /**
  30875. * Returns a new Index Buffer.
  30876. * Type returned : WebGLBuffer.
  30877. */
  30878. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30879. if (!this._linesIndexBuffer) {
  30880. var linesIndices = [];
  30881. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30882. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30883. }
  30884. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30885. this.linesIndexCount = linesIndices.length;
  30886. }
  30887. return this._linesIndexBuffer;
  30888. };
  30889. /**
  30890. * True is the passed Ray intersects the submesh bounding box.
  30891. * Boolean returned.
  30892. */
  30893. SubMesh.prototype.canIntersects = function (ray) {
  30894. var boundingInfo = this.getBoundingInfo();
  30895. if (!boundingInfo) {
  30896. return false;
  30897. }
  30898. return ray.intersectsBox(boundingInfo.boundingBox);
  30899. };
  30900. /**
  30901. * Returns an object IntersectionInfo.
  30902. */
  30903. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  30904. var intersectInfo = null;
  30905. // LineMesh first as it's also a Mesh...
  30906. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  30907. var lineMesh = this._mesh;
  30908. // Line test
  30909. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  30910. var p0 = positions[indices[index]];
  30911. var p1 = positions[indices[index + 1]];
  30912. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  30913. if (length < 0) {
  30914. continue;
  30915. }
  30916. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  30917. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  30918. if (fastCheck) {
  30919. break;
  30920. }
  30921. }
  30922. }
  30923. }
  30924. else {
  30925. // Triangles test
  30926. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30927. var p0 = positions[indices[index]];
  30928. var p1 = positions[indices[index + 1]];
  30929. var p2 = positions[indices[index + 2]];
  30930. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  30931. if (currentIntersectInfo) {
  30932. if (currentIntersectInfo.distance < 0) {
  30933. continue;
  30934. }
  30935. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  30936. intersectInfo = currentIntersectInfo;
  30937. intersectInfo.faceId = index / 3;
  30938. if (fastCheck) {
  30939. break;
  30940. }
  30941. }
  30942. }
  30943. }
  30944. }
  30945. return intersectInfo;
  30946. };
  30947. SubMesh.prototype._rebuild = function () {
  30948. if (this._linesIndexBuffer) {
  30949. this._linesIndexBuffer = null;
  30950. }
  30951. };
  30952. // Clone
  30953. /**
  30954. * Creates a new Submesh from the passed Mesh.
  30955. */
  30956. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  30957. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  30958. if (!this.IsGlobal) {
  30959. var boundingInfo = this.getBoundingInfo();
  30960. if (!boundingInfo) {
  30961. return result;
  30962. }
  30963. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  30964. }
  30965. return result;
  30966. };
  30967. // Dispose
  30968. /**
  30969. * Disposes the Submesh.
  30970. * Returns nothing.
  30971. */
  30972. SubMesh.prototype.dispose = function () {
  30973. if (this._linesIndexBuffer) {
  30974. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  30975. this._linesIndexBuffer = null;
  30976. }
  30977. // Remove from mesh
  30978. var index = this._mesh.subMeshes.indexOf(this);
  30979. this._mesh.subMeshes.splice(index, 1);
  30980. };
  30981. // Statics
  30982. /**
  30983. * Creates a new Submesh from the passed parameters :
  30984. * - materialIndex (integer) : the index of the main mesh material.
  30985. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  30986. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  30987. * - mesh (Mesh) : the main mesh to create the submesh from.
  30988. * - renderingMesh (optional Mesh) : rendering mesh.
  30989. */
  30990. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  30991. var minVertexIndex = Number.MAX_VALUE;
  30992. var maxVertexIndex = -Number.MAX_VALUE;
  30993. renderingMesh = (renderingMesh || mesh);
  30994. var indices = renderingMesh.getIndices();
  30995. for (var index = startIndex; index < startIndex + indexCount; index++) {
  30996. var vertexIndex = indices[index];
  30997. if (vertexIndex < minVertexIndex)
  30998. minVertexIndex = vertexIndex;
  30999. if (vertexIndex > maxVertexIndex)
  31000. maxVertexIndex = vertexIndex;
  31001. }
  31002. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  31003. };
  31004. return SubMesh;
  31005. }(BaseSubMesh));
  31006. BABYLON.SubMesh = SubMesh;
  31007. })(BABYLON || (BABYLON = {}));
  31008. //# sourceMappingURL=babylon.subMesh.js.map
  31009. var __assign = (this && this.__assign) || Object.assign || function(t) {
  31010. for (var s, i = 1, n = arguments.length; i < n; i++) {
  31011. s = arguments[i];
  31012. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  31013. t[p] = s[p];
  31014. }
  31015. return t;
  31016. };
  31017. var BABYLON;
  31018. (function (BABYLON) {
  31019. /**
  31020. * Manages the defines for the Material.
  31021. */
  31022. var MaterialDefines = /** @class */ (function () {
  31023. function MaterialDefines() {
  31024. this._isDirty = true;
  31025. this._areLightsDirty = true;
  31026. this._areAttributesDirty = true;
  31027. this._areTexturesDirty = true;
  31028. this._areFresnelDirty = true;
  31029. this._areMiscDirty = true;
  31030. this._areImageProcessingDirty = true;
  31031. this._normals = false;
  31032. this._uvs = false;
  31033. this._needNormals = false;
  31034. this._needUVs = false;
  31035. }
  31036. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  31037. /**
  31038. * Specifies if the material needs to be re-calculated.
  31039. */
  31040. get: function () {
  31041. return this._isDirty;
  31042. },
  31043. enumerable: true,
  31044. configurable: true
  31045. });
  31046. /**
  31047. * Marks the material to indicate that it has been re-calculated.
  31048. */
  31049. MaterialDefines.prototype.markAsProcessed = function () {
  31050. this._isDirty = false;
  31051. this._areAttributesDirty = false;
  31052. this._areTexturesDirty = false;
  31053. this._areFresnelDirty = false;
  31054. this._areLightsDirty = false;
  31055. this._areMiscDirty = false;
  31056. this._areImageProcessingDirty = false;
  31057. };
  31058. /**
  31059. * Marks the material to indicate that it needs to be re-calculated.
  31060. */
  31061. MaterialDefines.prototype.markAsUnprocessed = function () {
  31062. this._isDirty = true;
  31063. };
  31064. /**
  31065. * Marks the material to indicate all of its defines need to be re-calculated.
  31066. */
  31067. MaterialDefines.prototype.markAllAsDirty = function () {
  31068. this._areTexturesDirty = true;
  31069. this._areAttributesDirty = true;
  31070. this._areLightsDirty = true;
  31071. this._areFresnelDirty = true;
  31072. this._areMiscDirty = true;
  31073. this._areImageProcessingDirty = true;
  31074. this._isDirty = true;
  31075. };
  31076. /**
  31077. * Marks the material to indicate that image processing needs to be re-calculated.
  31078. */
  31079. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  31080. this._areImageProcessingDirty = true;
  31081. this._isDirty = true;
  31082. };
  31083. /**
  31084. * Marks the material to indicate the lights need to be re-calculated.
  31085. */
  31086. MaterialDefines.prototype.markAsLightDirty = function () {
  31087. this._areLightsDirty = true;
  31088. this._isDirty = true;
  31089. };
  31090. /**
  31091. * Marks the attribute state as changed.
  31092. */
  31093. MaterialDefines.prototype.markAsAttributesDirty = function () {
  31094. this._areAttributesDirty = true;
  31095. this._isDirty = true;
  31096. };
  31097. /**
  31098. * Marks the texture state as changed.
  31099. */
  31100. MaterialDefines.prototype.markAsTexturesDirty = function () {
  31101. this._areTexturesDirty = true;
  31102. this._isDirty = true;
  31103. };
  31104. /**
  31105. * Marks the fresnel state as changed.
  31106. */
  31107. MaterialDefines.prototype.markAsFresnelDirty = function () {
  31108. this._areFresnelDirty = true;
  31109. this._isDirty = true;
  31110. };
  31111. /**
  31112. * Marks the misc state as changed.
  31113. */
  31114. MaterialDefines.prototype.markAsMiscDirty = function () {
  31115. this._areMiscDirty = true;
  31116. this._isDirty = true;
  31117. };
  31118. /**
  31119. * Rebuilds the material defines.
  31120. */
  31121. MaterialDefines.prototype.rebuild = function () {
  31122. if (this._keys) {
  31123. delete this._keys;
  31124. }
  31125. this._keys = [];
  31126. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  31127. var key = _a[_i];
  31128. if (key[0] === "_") {
  31129. continue;
  31130. }
  31131. this._keys.push(key);
  31132. }
  31133. };
  31134. /**
  31135. * Specifies if two material defines are equal.
  31136. * @param other - A material define instance to compare to.
  31137. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  31138. */
  31139. MaterialDefines.prototype.isEqual = function (other) {
  31140. if (this._keys.length !== other._keys.length) {
  31141. return false;
  31142. }
  31143. for (var index = 0; index < this._keys.length; index++) {
  31144. var prop = this._keys[index];
  31145. if (this[prop] !== other[prop]) {
  31146. return false;
  31147. }
  31148. }
  31149. return true;
  31150. };
  31151. /**
  31152. * Clones this instance's defines to another instance.
  31153. * @param other - material defines to clone values to.
  31154. */
  31155. MaterialDefines.prototype.cloneTo = function (other) {
  31156. if (this._keys.length !== other._keys.length) {
  31157. other._keys = this._keys.slice(0);
  31158. }
  31159. for (var index = 0; index < this._keys.length; index++) {
  31160. var prop = this._keys[index];
  31161. other[prop] = this[prop];
  31162. }
  31163. };
  31164. /**
  31165. * Resets the material define values.
  31166. */
  31167. MaterialDefines.prototype.reset = function () {
  31168. for (var index = 0; index < this._keys.length; index++) {
  31169. var prop = this._keys[index];
  31170. if (typeof (this[prop]) === "number") {
  31171. this[prop] = 0;
  31172. }
  31173. else {
  31174. this[prop] = false;
  31175. }
  31176. }
  31177. };
  31178. /**
  31179. * Converts the material define values to a string.
  31180. * @returns - String of material define information.
  31181. */
  31182. MaterialDefines.prototype.toString = function () {
  31183. var result = "";
  31184. for (var index = 0; index < this._keys.length; index++) {
  31185. var prop = this._keys[index];
  31186. var value = this[prop];
  31187. if (typeof (value) === "number") {
  31188. result += "#define " + prop + " " + this[prop] + "\n";
  31189. }
  31190. else if (value) {
  31191. result += "#define " + prop + "\n";
  31192. }
  31193. }
  31194. return result;
  31195. };
  31196. return MaterialDefines;
  31197. }());
  31198. BABYLON.MaterialDefines = MaterialDefines;
  31199. /**
  31200. * This offers the main features of a material in BJS.
  31201. */
  31202. var Material = /** @class */ (function () {
  31203. /**
  31204. * Creates a material instance.
  31205. * @param name - The name of the material.
  31206. * @param scene - The BJS scene to reference.
  31207. * @param doNotAdd - Specifies if the material should be added to the scene.
  31208. */
  31209. function Material(name, scene, doNotAdd) {
  31210. /**
  31211. * Specifies if the ready state should be checked on each call.
  31212. */
  31213. this.checkReadyOnEveryCall = false;
  31214. /**
  31215. * Specifies if the ready state should be checked once.
  31216. */
  31217. this.checkReadyOnlyOnce = false;
  31218. /**
  31219. * The state of the material.
  31220. */
  31221. this.state = "";
  31222. /**
  31223. * The alpha value of the material.
  31224. */
  31225. this._alpha = 1.0;
  31226. /**
  31227. * Specifies if back face culling is enabled.
  31228. */
  31229. this._backFaceCulling = true;
  31230. /**
  31231. * Specifies if the material should be serialized.
  31232. */
  31233. this.doNotSerialize = false;
  31234. /**
  31235. * Specifies if the effect should be stored on sub meshes.
  31236. */
  31237. this.storeEffectOnSubMeshes = false;
  31238. /**
  31239. * An event triggered when the material is disposed.
  31240. * @type {BABYLON.Observable}
  31241. */
  31242. this.onDisposeObservable = new BABYLON.Observable();
  31243. /**
  31244. * An event triggered when the material is bound.
  31245. * @type {BABYLON.Observable}
  31246. */
  31247. this.onBindObservable = new BABYLON.Observable();
  31248. /**
  31249. * An event triggered when the material is unbound.
  31250. * @type {BABYLON.Observable}
  31251. */
  31252. this.onUnBindObservable = new BABYLON.Observable();
  31253. /**
  31254. * Stores the value of the alpha mode.
  31255. */
  31256. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  31257. /**
  31258. * Stores the state of the need depth pre-pass value.
  31259. */
  31260. this._needDepthPrePass = false;
  31261. /**
  31262. * Specifies if depth writing should be disabled.
  31263. */
  31264. this.disableDepthWrite = false;
  31265. /**
  31266. * Specifies if depth writing should be forced.
  31267. */
  31268. this.forceDepthWrite = false;
  31269. /**
  31270. * Specifies if there should be a separate pass for culling.
  31271. */
  31272. this.separateCullingPass = false;
  31273. /**
  31274. * Stores the state specifing if fog should be enabled.
  31275. */
  31276. this._fogEnabled = true;
  31277. /**
  31278. * Stores the size of points.
  31279. */
  31280. this.pointSize = 1.0;
  31281. /**
  31282. * Stores the z offset value.
  31283. */
  31284. this.zOffset = 0;
  31285. /**
  31286. * Specifies if the material was previously ready.
  31287. */
  31288. this._wasPreviouslyReady = false;
  31289. /**
  31290. * Stores the fill mode state.
  31291. */
  31292. this._fillMode = Material.TriangleFillMode;
  31293. this.name = name;
  31294. this.id = name || BABYLON.Tools.RandomId();
  31295. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  31296. if (this._scene.useRightHandedSystem) {
  31297. this.sideOrientation = Material.ClockWiseSideOrientation;
  31298. }
  31299. else {
  31300. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  31301. }
  31302. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  31303. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  31304. if (!doNotAdd) {
  31305. this._scene.materials.push(this);
  31306. }
  31307. }
  31308. Object.defineProperty(Material, "TriangleFillMode", {
  31309. /**
  31310. * Returns the triangle fill mode.
  31311. */
  31312. get: function () {
  31313. return Material._TriangleFillMode;
  31314. },
  31315. enumerable: true,
  31316. configurable: true
  31317. });
  31318. Object.defineProperty(Material, "WireFrameFillMode", {
  31319. /**
  31320. * Returns the wireframe mode.
  31321. */
  31322. get: function () {
  31323. return Material._WireFrameFillMode;
  31324. },
  31325. enumerable: true,
  31326. configurable: true
  31327. });
  31328. Object.defineProperty(Material, "PointFillMode", {
  31329. /**
  31330. * Returns the point fill mode.
  31331. */
  31332. get: function () {
  31333. return Material._PointFillMode;
  31334. },
  31335. enumerable: true,
  31336. configurable: true
  31337. });
  31338. Object.defineProperty(Material, "PointListDrawMode", {
  31339. /**
  31340. * Returns the point list draw mode.
  31341. */
  31342. get: function () {
  31343. return Material._PointListDrawMode;
  31344. },
  31345. enumerable: true,
  31346. configurable: true
  31347. });
  31348. Object.defineProperty(Material, "LineListDrawMode", {
  31349. /**
  31350. * Returns the line list draw mode.
  31351. */
  31352. get: function () {
  31353. return Material._LineListDrawMode;
  31354. },
  31355. enumerable: true,
  31356. configurable: true
  31357. });
  31358. Object.defineProperty(Material, "LineLoopDrawMode", {
  31359. /**
  31360. * Returns the line loop draw mode.
  31361. */
  31362. get: function () {
  31363. return Material._LineLoopDrawMode;
  31364. },
  31365. enumerable: true,
  31366. configurable: true
  31367. });
  31368. Object.defineProperty(Material, "LineStripDrawMode", {
  31369. /**
  31370. * Returns the line strip draw mode.
  31371. */
  31372. get: function () {
  31373. return Material._LineStripDrawMode;
  31374. },
  31375. enumerable: true,
  31376. configurable: true
  31377. });
  31378. Object.defineProperty(Material, "TriangleStripDrawMode", {
  31379. /**
  31380. * Returns the triangle strip draw mode.
  31381. */
  31382. get: function () {
  31383. return Material._TriangleStripDrawMode;
  31384. },
  31385. enumerable: true,
  31386. configurable: true
  31387. });
  31388. Object.defineProperty(Material, "TriangleFanDrawMode", {
  31389. /**
  31390. * Returns the triangle fan draw mode.
  31391. */
  31392. get: function () {
  31393. return Material._TriangleFanDrawMode;
  31394. },
  31395. enumerable: true,
  31396. configurable: true
  31397. });
  31398. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  31399. /**
  31400. * Returns the clock-wise side orientation.
  31401. */
  31402. get: function () {
  31403. return Material._ClockWiseSideOrientation;
  31404. },
  31405. enumerable: true,
  31406. configurable: true
  31407. });
  31408. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  31409. /**
  31410. * Returns the counter clock-wise side orientation.
  31411. */
  31412. get: function () {
  31413. return Material._CounterClockWiseSideOrientation;
  31414. },
  31415. enumerable: true,
  31416. configurable: true
  31417. });
  31418. Object.defineProperty(Material, "TextureDirtyFlag", {
  31419. /**
  31420. * Returns the dirty texture flag value.
  31421. */
  31422. get: function () {
  31423. return Material._TextureDirtyFlag;
  31424. },
  31425. enumerable: true,
  31426. configurable: true
  31427. });
  31428. Object.defineProperty(Material, "LightDirtyFlag", {
  31429. /**
  31430. * Returns the dirty light flag value.
  31431. */
  31432. get: function () {
  31433. return Material._LightDirtyFlag;
  31434. },
  31435. enumerable: true,
  31436. configurable: true
  31437. });
  31438. Object.defineProperty(Material, "FresnelDirtyFlag", {
  31439. /**
  31440. * Returns the dirty fresnel flag value.
  31441. */
  31442. get: function () {
  31443. return Material._FresnelDirtyFlag;
  31444. },
  31445. enumerable: true,
  31446. configurable: true
  31447. });
  31448. Object.defineProperty(Material, "AttributesDirtyFlag", {
  31449. /**
  31450. * Returns the dirty attributes flag value.
  31451. */
  31452. get: function () {
  31453. return Material._AttributesDirtyFlag;
  31454. },
  31455. enumerable: true,
  31456. configurable: true
  31457. });
  31458. Object.defineProperty(Material, "MiscDirtyFlag", {
  31459. /**
  31460. * Returns the dirty misc flag value.
  31461. */
  31462. get: function () {
  31463. return Material._MiscDirtyFlag;
  31464. },
  31465. enumerable: true,
  31466. configurable: true
  31467. });
  31468. Object.defineProperty(Material.prototype, "alpha", {
  31469. /**
  31470. * Gets the alpha value of the material.
  31471. */
  31472. get: function () {
  31473. return this._alpha;
  31474. },
  31475. /**
  31476. * Sets the alpha value of the material.
  31477. */
  31478. set: function (value) {
  31479. if (this._alpha === value) {
  31480. return;
  31481. }
  31482. this._alpha = value;
  31483. this.markAsDirty(Material.MiscDirtyFlag);
  31484. },
  31485. enumerable: true,
  31486. configurable: true
  31487. });
  31488. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31489. /**
  31490. * Gets the back-face culling state.
  31491. */
  31492. get: function () {
  31493. return this._backFaceCulling;
  31494. },
  31495. /**
  31496. * Sets the back-face culling state.
  31497. */
  31498. set: function (value) {
  31499. if (this._backFaceCulling === value) {
  31500. return;
  31501. }
  31502. this._backFaceCulling = value;
  31503. this.markAsDirty(Material.TextureDirtyFlag);
  31504. },
  31505. enumerable: true,
  31506. configurable: true
  31507. });
  31508. Object.defineProperty(Material.prototype, "onDispose", {
  31509. /**
  31510. * Called during a dispose event.
  31511. */
  31512. set: function (callback) {
  31513. if (this._onDisposeObserver) {
  31514. this.onDisposeObservable.remove(this._onDisposeObserver);
  31515. }
  31516. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31517. },
  31518. enumerable: true,
  31519. configurable: true
  31520. });
  31521. Object.defineProperty(Material.prototype, "onBind", {
  31522. /**
  31523. * Called during a bind event.
  31524. */
  31525. set: function (callback) {
  31526. if (this._onBindObserver) {
  31527. this.onBindObservable.remove(this._onBindObserver);
  31528. }
  31529. this._onBindObserver = this.onBindObservable.add(callback);
  31530. },
  31531. enumerable: true,
  31532. configurable: true
  31533. });
  31534. Object.defineProperty(Material.prototype, "alphaMode", {
  31535. /**
  31536. * Gets the value of the alpha mode.
  31537. */
  31538. get: function () {
  31539. return this._alphaMode;
  31540. },
  31541. /**
  31542. * Sets the value of the alpha mode.
  31543. */
  31544. set: function (value) {
  31545. if (this._alphaMode === value) {
  31546. return;
  31547. }
  31548. this._alphaMode = value;
  31549. this.markAsDirty(Material.TextureDirtyFlag);
  31550. },
  31551. enumerable: true,
  31552. configurable: true
  31553. });
  31554. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31555. /**
  31556. * Gets the depth pre-pass value.
  31557. */
  31558. get: function () {
  31559. return this._needDepthPrePass;
  31560. },
  31561. /**
  31562. * Sets the need depth pre-pass value.
  31563. */
  31564. set: function (value) {
  31565. if (this._needDepthPrePass === value) {
  31566. return;
  31567. }
  31568. this._needDepthPrePass = value;
  31569. if (this._needDepthPrePass) {
  31570. this.checkReadyOnEveryCall = true;
  31571. }
  31572. },
  31573. enumerable: true,
  31574. configurable: true
  31575. });
  31576. Object.defineProperty(Material.prototype, "fogEnabled", {
  31577. /**
  31578. * Gets the value of the fog enabled state.
  31579. */
  31580. get: function () {
  31581. return this._fogEnabled;
  31582. },
  31583. /**
  31584. * Sets the state for enabling fog.
  31585. */
  31586. set: function (value) {
  31587. if (this._fogEnabled === value) {
  31588. return;
  31589. }
  31590. this._fogEnabled = value;
  31591. this.markAsDirty(Material.MiscDirtyFlag);
  31592. },
  31593. enumerable: true,
  31594. configurable: true
  31595. });
  31596. Object.defineProperty(Material.prototype, "wireframe", {
  31597. /**
  31598. * Gets a value specifying if wireframe mode is enabled.
  31599. */
  31600. get: function () {
  31601. return this._fillMode === Material.WireFrameFillMode;
  31602. },
  31603. /**
  31604. * Sets the state of wireframe mode.
  31605. */
  31606. set: function (value) {
  31607. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31608. },
  31609. enumerable: true,
  31610. configurable: true
  31611. });
  31612. Object.defineProperty(Material.prototype, "pointsCloud", {
  31613. /**
  31614. * Gets the value specifying if point clouds are enabled.
  31615. */
  31616. get: function () {
  31617. return this._fillMode === Material.PointFillMode;
  31618. },
  31619. /**
  31620. * Sets the state of point cloud mode.
  31621. */
  31622. set: function (value) {
  31623. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31624. },
  31625. enumerable: true,
  31626. configurable: true
  31627. });
  31628. Object.defineProperty(Material.prototype, "fillMode", {
  31629. /**
  31630. * Gets the material fill mode.
  31631. */
  31632. get: function () {
  31633. return this._fillMode;
  31634. },
  31635. /**
  31636. * Sets the material fill mode.
  31637. */
  31638. set: function (value) {
  31639. if (this._fillMode === value) {
  31640. return;
  31641. }
  31642. this._fillMode = value;
  31643. this.markAsDirty(Material.MiscDirtyFlag);
  31644. },
  31645. enumerable: true,
  31646. configurable: true
  31647. });
  31648. /**
  31649. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31650. * subclasses should override adding information pertainent to themselves.
  31651. * @returns - String with material information.
  31652. */
  31653. Material.prototype.toString = function (fullDetails) {
  31654. var ret = "Name: " + this.name;
  31655. if (fullDetails) {
  31656. }
  31657. return ret;
  31658. };
  31659. /**
  31660. * Gets the class name of the material.
  31661. * @returns - String with the class name of the material.
  31662. */
  31663. Material.prototype.getClassName = function () {
  31664. return "Material";
  31665. };
  31666. Object.defineProperty(Material.prototype, "isFrozen", {
  31667. /**
  31668. * Specifies if updates for the material been locked.
  31669. */
  31670. get: function () {
  31671. return this.checkReadyOnlyOnce;
  31672. },
  31673. enumerable: true,
  31674. configurable: true
  31675. });
  31676. /**
  31677. * Locks updates for the material.
  31678. */
  31679. Material.prototype.freeze = function () {
  31680. this.checkReadyOnlyOnce = true;
  31681. };
  31682. /**
  31683. * Unlocks updates for the material.
  31684. */
  31685. Material.prototype.unfreeze = function () {
  31686. this.checkReadyOnlyOnce = false;
  31687. };
  31688. /**
  31689. * Specifies if the material is ready to be used.
  31690. * @param mesh - BJS mesh.
  31691. * @param useInstances - Specifies if instances should be used.
  31692. * @returns - Boolean indicating if the material is ready to be used.
  31693. */
  31694. Material.prototype.isReady = function (mesh, useInstances) {
  31695. return true;
  31696. };
  31697. /**
  31698. * Specifies that the submesh is ready to be used.
  31699. * @param mesh - BJS mesh.
  31700. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31701. * @param useInstances - Specifies that instances should be used.
  31702. * @returns - boolean indicating that the submesh is ready or not.
  31703. */
  31704. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31705. return false;
  31706. };
  31707. /**
  31708. * Returns the material effect.
  31709. * @returns - Nullable material effect.
  31710. */
  31711. Material.prototype.getEffect = function () {
  31712. return this._effect;
  31713. };
  31714. /**
  31715. * Returns the BJS scene.
  31716. * @returns - BJS Scene.
  31717. */
  31718. Material.prototype.getScene = function () {
  31719. return this._scene;
  31720. };
  31721. /**
  31722. * Specifies if the material will require alpha blending
  31723. * @returns - Boolean specifying if alpha blending is needed.
  31724. */
  31725. Material.prototype.needAlphaBlending = function () {
  31726. return (this.alpha < 1.0);
  31727. };
  31728. /**
  31729. * Specifies if the mesh will require alpha blending.
  31730. * @param mesh - BJS mesh.
  31731. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31732. */
  31733. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31734. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31735. };
  31736. /**
  31737. * Specifies if this material should be rendered in alpha test mode.
  31738. * @returns - Boolean specifying if an alpha test is needed.
  31739. */
  31740. Material.prototype.needAlphaTesting = function () {
  31741. return false;
  31742. };
  31743. /**
  31744. * Gets the texture used for the alpha test.
  31745. * @returns - Nullable alpha test texture.
  31746. */
  31747. Material.prototype.getAlphaTestTexture = function () {
  31748. return null;
  31749. };
  31750. /**
  31751. * Marks the material to indicate that it needs to be re-calculated.
  31752. */
  31753. Material.prototype.markDirty = function () {
  31754. this._wasPreviouslyReady = false;
  31755. };
  31756. Material.prototype._preBind = function (effect, overrideOrientation) {
  31757. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31758. var engine = this._scene.getEngine();
  31759. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31760. var reverse = orientation === Material.ClockWiseSideOrientation;
  31761. engine.enableEffect(effect ? effect : this._effect);
  31762. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31763. return reverse;
  31764. };
  31765. /**
  31766. * Binds the material to the mesh.
  31767. * @param world - World transformation matrix.
  31768. * @param mesh - Mesh to bind the material to.
  31769. */
  31770. Material.prototype.bind = function (world, mesh) {
  31771. };
  31772. /**
  31773. * Binds the submesh to the material.
  31774. * @param world - World transformation matrix.
  31775. * @param mesh - Mesh containing the submesh.
  31776. * @param subMesh - Submesh to bind the material to.
  31777. */
  31778. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31779. };
  31780. /**
  31781. * Binds the world matrix to the material.
  31782. * @param world - World transformation matrix.
  31783. */
  31784. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31785. };
  31786. /**
  31787. * Binds the scene's uniform buffer to the effect.
  31788. * @param effect - Effect to bind to the scene uniform buffer.
  31789. * @param sceneUbo - Scene uniform buffer.
  31790. */
  31791. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  31792. sceneUbo.bindToEffect(effect, "Scene");
  31793. };
  31794. /**
  31795. * Binds the view matrix to the effect.
  31796. * @param effect - Effect to bind the view matrix to.
  31797. */
  31798. Material.prototype.bindView = function (effect) {
  31799. if (!this._useUBO) {
  31800. effect.setMatrix("view", this.getScene().getViewMatrix());
  31801. }
  31802. else {
  31803. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31804. }
  31805. };
  31806. /**
  31807. * Binds the view projection matrix to the effect.
  31808. * @param effect - Effect to bind the view projection matrix to.
  31809. */
  31810. Material.prototype.bindViewProjection = function (effect) {
  31811. if (!this._useUBO) {
  31812. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  31813. }
  31814. else {
  31815. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31816. }
  31817. };
  31818. /**
  31819. * Specifies if material alpha testing should be turned on for the mesh.
  31820. * @param mesh - BJS mesh.
  31821. */
  31822. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  31823. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  31824. };
  31825. /**
  31826. * Processes to execute after binding the material to a mesh.
  31827. * @param mesh - BJS mesh.
  31828. */
  31829. Material.prototype._afterBind = function (mesh) {
  31830. this._scene._cachedMaterial = this;
  31831. if (mesh) {
  31832. this._scene._cachedVisibility = mesh.visibility;
  31833. }
  31834. else {
  31835. this._scene._cachedVisibility = 1;
  31836. }
  31837. if (mesh) {
  31838. this.onBindObservable.notifyObservers(mesh);
  31839. }
  31840. if (this.disableDepthWrite) {
  31841. var engine = this._scene.getEngine();
  31842. this._cachedDepthWriteState = engine.getDepthWrite();
  31843. engine.setDepthWrite(false);
  31844. }
  31845. };
  31846. /**
  31847. * Unbinds the material from the mesh.
  31848. */
  31849. Material.prototype.unbind = function () {
  31850. this.onUnBindObservable.notifyObservers(this);
  31851. if (this.disableDepthWrite) {
  31852. var engine = this._scene.getEngine();
  31853. engine.setDepthWrite(this._cachedDepthWriteState);
  31854. }
  31855. };
  31856. /**
  31857. * Gets the active textures from the material.
  31858. * @returns - Array of textures.
  31859. */
  31860. Material.prototype.getActiveTextures = function () {
  31861. return [];
  31862. };
  31863. /**
  31864. * Specifies if the material uses a texture.
  31865. * @param texture - Texture to check against the material.
  31866. * @returns - Boolean specifying if the material uses the texture.
  31867. */
  31868. Material.prototype.hasTexture = function (texture) {
  31869. return false;
  31870. };
  31871. /**
  31872. * Makes a duplicate of the material, and gives it a new name.
  31873. * @param name - Name to call the duplicated material.
  31874. * @returns - Nullable cloned material
  31875. */
  31876. Material.prototype.clone = function (name) {
  31877. return null;
  31878. };
  31879. /**
  31880. * Gets the meshes bound to the material.
  31881. * @returns - Array of meshes bound to the material.
  31882. */
  31883. Material.prototype.getBindedMeshes = function () {
  31884. var result = new Array();
  31885. for (var index = 0; index < this._scene.meshes.length; index++) {
  31886. var mesh = this._scene.meshes[index];
  31887. if (mesh.material === this) {
  31888. result.push(mesh);
  31889. }
  31890. }
  31891. return result;
  31892. };
  31893. /**
  31894. * Force shader compilation
  31895. * @param mesh - BJS mesh.
  31896. * @param onCompiled - function to execute once the material is compiled.
  31897. * @param options - options to pass to this function.
  31898. */
  31899. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  31900. var _this = this;
  31901. var localOptions = __assign({ clipPlane: false }, options);
  31902. var subMesh = new BABYLON.BaseSubMesh();
  31903. var scene = this.getScene();
  31904. var checkReady = function () {
  31905. if (!_this._scene || !_this._scene.getEngine()) {
  31906. return;
  31907. }
  31908. if (subMesh._materialDefines) {
  31909. subMesh._materialDefines._renderId = -1;
  31910. }
  31911. var clipPlaneState = scene.clipPlane;
  31912. if (localOptions.clipPlane) {
  31913. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  31914. }
  31915. if (_this.storeEffectOnSubMeshes) {
  31916. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  31917. if (onCompiled) {
  31918. onCompiled(_this);
  31919. }
  31920. }
  31921. else {
  31922. setTimeout(checkReady, 16);
  31923. }
  31924. }
  31925. else {
  31926. if (_this.isReady(mesh)) {
  31927. if (onCompiled) {
  31928. onCompiled(_this);
  31929. }
  31930. }
  31931. else {
  31932. setTimeout(checkReady, 16);
  31933. }
  31934. }
  31935. if (localOptions.clipPlane) {
  31936. scene.clipPlane = clipPlaneState;
  31937. }
  31938. };
  31939. checkReady();
  31940. };
  31941. /**
  31942. * Force shader compilation.
  31943. * @param mesh The mesh that will use this material
  31944. * @param options Additional options for compiling the shaders
  31945. * @returns A promise that resolves when the compilation completes
  31946. */
  31947. Material.prototype.forceCompilationAsync = function (mesh, options) {
  31948. var _this = this;
  31949. return new Promise(function (resolve) {
  31950. _this.forceCompilation(mesh, function () {
  31951. resolve();
  31952. }, options);
  31953. });
  31954. };
  31955. /**
  31956. * Marks a define in the material to indicate that it needs to be re-computed.
  31957. * @param flag - Material define flag.
  31958. */
  31959. Material.prototype.markAsDirty = function (flag) {
  31960. if (flag & Material.TextureDirtyFlag) {
  31961. this._markAllSubMeshesAsTexturesDirty();
  31962. }
  31963. if (flag & Material.LightDirtyFlag) {
  31964. this._markAllSubMeshesAsLightsDirty();
  31965. }
  31966. if (flag & Material.FresnelDirtyFlag) {
  31967. this._markAllSubMeshesAsFresnelDirty();
  31968. }
  31969. if (flag & Material.AttributesDirtyFlag) {
  31970. this._markAllSubMeshesAsAttributesDirty();
  31971. }
  31972. if (flag & Material.MiscDirtyFlag) {
  31973. this._markAllSubMeshesAsMiscDirty();
  31974. }
  31975. this.getScene().resetCachedMaterial();
  31976. };
  31977. /**
  31978. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  31979. * @param func - function which checks material defines against the submeshes.
  31980. */
  31981. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  31982. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  31983. var mesh = _a[_i];
  31984. if (!mesh.subMeshes) {
  31985. continue;
  31986. }
  31987. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  31988. var subMesh = _c[_b];
  31989. if (subMesh.getMaterial() !== this) {
  31990. continue;
  31991. }
  31992. if (!subMesh._materialDefines) {
  31993. continue;
  31994. }
  31995. func(subMesh._materialDefines);
  31996. }
  31997. }
  31998. };
  31999. /**
  32000. * Indicates that image processing needs to be re-calculated for all submeshes.
  32001. */
  32002. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  32003. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  32004. };
  32005. /**
  32006. * Indicates that textures need to be re-calculated for all submeshes.
  32007. */
  32008. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  32009. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  32010. };
  32011. /**
  32012. * Indicates that fresnel needs to be re-calculated for all submeshes.
  32013. */
  32014. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  32015. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  32016. };
  32017. /**
  32018. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  32019. */
  32020. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  32021. this._markAllSubMeshesAsDirty(function (defines) {
  32022. defines.markAsFresnelDirty();
  32023. defines.markAsMiscDirty();
  32024. });
  32025. };
  32026. /**
  32027. * Indicates that lights need to be re-calculated for all submeshes.
  32028. */
  32029. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  32030. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  32031. };
  32032. /**
  32033. * Indicates that attributes need to be re-calculated for all submeshes.
  32034. */
  32035. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  32036. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  32037. };
  32038. /**
  32039. * Indicates that misc needs to be re-calculated for all submeshes.
  32040. */
  32041. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  32042. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  32043. };
  32044. /**
  32045. * Indicates that textures and misc need to be re-calculated for all submeshes.
  32046. */
  32047. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  32048. this._markAllSubMeshesAsDirty(function (defines) {
  32049. defines.markAsTexturesDirty();
  32050. defines.markAsMiscDirty();
  32051. });
  32052. };
  32053. /**
  32054. * Disposes the material.
  32055. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  32056. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  32057. */
  32058. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  32059. // Animations
  32060. this.getScene().stopAnimation(this);
  32061. this.getScene().freeProcessedMaterials();
  32062. // Remove from scene
  32063. var index = this._scene.materials.indexOf(this);
  32064. if (index >= 0) {
  32065. this._scene.materials.splice(index, 1);
  32066. }
  32067. // Remove from meshes
  32068. for (index = 0; index < this._scene.meshes.length; index++) {
  32069. var mesh = this._scene.meshes[index];
  32070. if (mesh.material === this) {
  32071. mesh.material = null;
  32072. if (mesh.geometry) {
  32073. var geometry = (mesh.geometry);
  32074. if (this.storeEffectOnSubMeshes) {
  32075. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  32076. var subMesh = _a[_i];
  32077. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  32078. if (forceDisposeEffect && subMesh._materialEffect) {
  32079. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  32080. }
  32081. }
  32082. }
  32083. else {
  32084. geometry._releaseVertexArrayObject(this._effect);
  32085. }
  32086. }
  32087. }
  32088. }
  32089. this._uniformBuffer.dispose();
  32090. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  32091. if (forceDisposeEffect && this._effect) {
  32092. if (!this.storeEffectOnSubMeshes) {
  32093. this._scene.getEngine()._releaseEffect(this._effect);
  32094. }
  32095. this._effect = null;
  32096. }
  32097. // Callback
  32098. this.onDisposeObservable.notifyObservers(this);
  32099. this.onDisposeObservable.clear();
  32100. this.onBindObservable.clear();
  32101. this.onUnBindObservable.clear();
  32102. };
  32103. /**
  32104. * Serializes this material.
  32105. * @returns - serialized material object.
  32106. */
  32107. Material.prototype.serialize = function () {
  32108. return BABYLON.SerializationHelper.Serialize(this);
  32109. };
  32110. /**
  32111. * Creates a MultiMaterial from parse MultiMaterial data.
  32112. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  32113. * @param scene - BJS scene.
  32114. * @returns - MultiMaterial.
  32115. */
  32116. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  32117. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  32118. multiMaterial.id = parsedMultiMaterial.id;
  32119. if (BABYLON.Tags) {
  32120. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  32121. }
  32122. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  32123. var subMatId = parsedMultiMaterial.materials[matIndex];
  32124. if (subMatId) {
  32125. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  32126. }
  32127. else {
  32128. multiMaterial.subMaterials.push(null);
  32129. }
  32130. }
  32131. return multiMaterial;
  32132. };
  32133. /**
  32134. * Creates a material from parsed material data.
  32135. * @param parsedMaterial - Parsed material data.
  32136. * @param scene - BJS scene.
  32137. * @param rootUrl - Root URL containing the material information.
  32138. * @returns - Parsed material.
  32139. */
  32140. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  32141. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  32142. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  32143. }
  32144. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  32145. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  32146. if (!BABYLON.LegacyPBRMaterial) {
  32147. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  32148. return;
  32149. }
  32150. }
  32151. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  32152. return materialType.Parse(parsedMaterial, scene, rootUrl);
  32153. ;
  32154. };
  32155. // Triangle views
  32156. Material._TriangleFillMode = 0;
  32157. Material._WireFrameFillMode = 1;
  32158. Material._PointFillMode = 2;
  32159. // Draw modes
  32160. Material._PointListDrawMode = 3;
  32161. Material._LineListDrawMode = 4;
  32162. Material._LineLoopDrawMode = 5;
  32163. Material._LineStripDrawMode = 6;
  32164. Material._TriangleStripDrawMode = 7;
  32165. Material._TriangleFanDrawMode = 8;
  32166. /**
  32167. * Stores the clock-wise side orientation.
  32168. */
  32169. Material._ClockWiseSideOrientation = 0;
  32170. /**
  32171. * Stores the counter clock-wise side orientation.
  32172. */
  32173. Material._CounterClockWiseSideOrientation = 1;
  32174. /**
  32175. * The dirty texture flag value.
  32176. */
  32177. Material._TextureDirtyFlag = 1;
  32178. /**
  32179. * The dirty light flag value.
  32180. */
  32181. Material._LightDirtyFlag = 2;
  32182. /**
  32183. * The dirty fresnel flag value.
  32184. */
  32185. Material._FresnelDirtyFlag = 4;
  32186. /**
  32187. * The dirty attribute flag value.
  32188. */
  32189. Material._AttributesDirtyFlag = 8;
  32190. /**
  32191. * The dirty misc flag value.
  32192. */
  32193. Material._MiscDirtyFlag = 16;
  32194. __decorate([
  32195. BABYLON.serialize()
  32196. ], Material.prototype, "id", void 0);
  32197. __decorate([
  32198. BABYLON.serialize()
  32199. ], Material.prototype, "name", void 0);
  32200. __decorate([
  32201. BABYLON.serialize()
  32202. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  32203. __decorate([
  32204. BABYLON.serialize()
  32205. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  32206. __decorate([
  32207. BABYLON.serialize()
  32208. ], Material.prototype, "state", void 0);
  32209. __decorate([
  32210. BABYLON.serialize("alpha")
  32211. ], Material.prototype, "_alpha", void 0);
  32212. __decorate([
  32213. BABYLON.serialize("backFaceCulling")
  32214. ], Material.prototype, "_backFaceCulling", void 0);
  32215. __decorate([
  32216. BABYLON.serialize()
  32217. ], Material.prototype, "sideOrientation", void 0);
  32218. __decorate([
  32219. BABYLON.serialize("alphaMode")
  32220. ], Material.prototype, "_alphaMode", void 0);
  32221. __decorate([
  32222. BABYLON.serialize()
  32223. ], Material.prototype, "_needDepthPrePass", void 0);
  32224. __decorate([
  32225. BABYLON.serialize()
  32226. ], Material.prototype, "disableDepthWrite", void 0);
  32227. __decorate([
  32228. BABYLON.serialize()
  32229. ], Material.prototype, "forceDepthWrite", void 0);
  32230. __decorate([
  32231. BABYLON.serialize()
  32232. ], Material.prototype, "separateCullingPass", void 0);
  32233. __decorate([
  32234. BABYLON.serialize("fogEnabled")
  32235. ], Material.prototype, "_fogEnabled", void 0);
  32236. __decorate([
  32237. BABYLON.serialize()
  32238. ], Material.prototype, "pointSize", void 0);
  32239. __decorate([
  32240. BABYLON.serialize()
  32241. ], Material.prototype, "zOffset", void 0);
  32242. __decorate([
  32243. BABYLON.serialize()
  32244. ], Material.prototype, "wireframe", null);
  32245. __decorate([
  32246. BABYLON.serialize()
  32247. ], Material.prototype, "pointsCloud", null);
  32248. __decorate([
  32249. BABYLON.serialize()
  32250. ], Material.prototype, "fillMode", null);
  32251. return Material;
  32252. }());
  32253. BABYLON.Material = Material;
  32254. })(BABYLON || (BABYLON = {}));
  32255. //# sourceMappingURL=babylon.material.js.map
  32256. var BABYLON;
  32257. (function (BABYLON) {
  32258. var UniformBuffer = /** @class */ (function () {
  32259. /**
  32260. * Uniform buffer objects.
  32261. *
  32262. * Handles blocks of uniform on the GPU.
  32263. *
  32264. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  32265. *
  32266. * For more information, please refer to :
  32267. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  32268. */
  32269. function UniformBuffer(engine, data, dynamic) {
  32270. this._engine = engine;
  32271. this._noUBO = !engine.supportsUniformBuffers;
  32272. this._dynamic = dynamic;
  32273. this._data = data || [];
  32274. this._uniformLocations = {};
  32275. this._uniformSizes = {};
  32276. this._uniformLocationPointer = 0;
  32277. this._needSync = false;
  32278. if (this._noUBO) {
  32279. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  32280. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  32281. this.updateFloat = this._updateFloatForEffect;
  32282. this.updateFloat2 = this._updateFloat2ForEffect;
  32283. this.updateFloat3 = this._updateFloat3ForEffect;
  32284. this.updateFloat4 = this._updateFloat4ForEffect;
  32285. this.updateMatrix = this._updateMatrixForEffect;
  32286. this.updateVector3 = this._updateVector3ForEffect;
  32287. this.updateVector4 = this._updateVector4ForEffect;
  32288. this.updateColor3 = this._updateColor3ForEffect;
  32289. this.updateColor4 = this._updateColor4ForEffect;
  32290. }
  32291. else {
  32292. this._engine._uniformBuffers.push(this);
  32293. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  32294. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  32295. this.updateFloat = this._updateFloatForUniform;
  32296. this.updateFloat2 = this._updateFloat2ForUniform;
  32297. this.updateFloat3 = this._updateFloat3ForUniform;
  32298. this.updateFloat4 = this._updateFloat4ForUniform;
  32299. this.updateMatrix = this._updateMatrixForUniform;
  32300. this.updateVector3 = this._updateVector3ForUniform;
  32301. this.updateVector4 = this._updateVector4ForUniform;
  32302. this.updateColor3 = this._updateColor3ForUniform;
  32303. this.updateColor4 = this._updateColor4ForUniform;
  32304. }
  32305. }
  32306. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  32307. // Properties
  32308. /**
  32309. * Indicates if the buffer is using the WebGL2 UBO implementation,
  32310. * or just falling back on setUniformXXX calls.
  32311. */
  32312. get: function () {
  32313. return !this._noUBO;
  32314. },
  32315. enumerable: true,
  32316. configurable: true
  32317. });
  32318. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  32319. /**
  32320. * Indicates if the WebGL underlying uniform buffer is in sync
  32321. * with the javascript cache data.
  32322. */
  32323. get: function () {
  32324. return !this._needSync;
  32325. },
  32326. enumerable: true,
  32327. configurable: true
  32328. });
  32329. /**
  32330. * Indicates if the WebGL underlying uniform buffer is dynamic.
  32331. * Also, a dynamic UniformBuffer will disable cache verification and always
  32332. * update the underlying WebGL uniform buffer to the GPU.
  32333. */
  32334. UniformBuffer.prototype.isDynamic = function () {
  32335. return this._dynamic !== undefined;
  32336. };
  32337. /**
  32338. * The data cache on JS side.
  32339. */
  32340. UniformBuffer.prototype.getData = function () {
  32341. return this._bufferData;
  32342. };
  32343. /**
  32344. * The underlying WebGL Uniform buffer.
  32345. */
  32346. UniformBuffer.prototype.getBuffer = function () {
  32347. return this._buffer;
  32348. };
  32349. /**
  32350. * std140 layout specifies how to align data within an UBO structure.
  32351. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  32352. * for specs.
  32353. */
  32354. UniformBuffer.prototype._fillAlignment = function (size) {
  32355. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  32356. // and 4x4 matrices
  32357. // TODO : change if other types are used
  32358. var alignment;
  32359. if (size <= 2) {
  32360. alignment = size;
  32361. }
  32362. else {
  32363. alignment = 4;
  32364. }
  32365. if ((this._uniformLocationPointer % alignment) !== 0) {
  32366. var oldPointer = this._uniformLocationPointer;
  32367. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  32368. var diff = this._uniformLocationPointer - oldPointer;
  32369. for (var i = 0; i < diff; i++) {
  32370. this._data.push(0);
  32371. }
  32372. }
  32373. };
  32374. /**
  32375. * Adds an uniform in the buffer.
  32376. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  32377. * for the layout to be correct !
  32378. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32379. * @param {number|number[]} size Data size, or data directly.
  32380. */
  32381. UniformBuffer.prototype.addUniform = function (name, size) {
  32382. if (this._noUBO) {
  32383. return;
  32384. }
  32385. if (this._uniformLocations[name] !== undefined) {
  32386. // Already existing uniform
  32387. return;
  32388. }
  32389. // This function must be called in the order of the shader layout !
  32390. // size can be the size of the uniform, or data directly
  32391. var data;
  32392. if (size instanceof Array) {
  32393. data = size;
  32394. size = data.length;
  32395. }
  32396. else {
  32397. size = size;
  32398. data = [];
  32399. // Fill with zeros
  32400. for (var i = 0; i < size; i++) {
  32401. data.push(0);
  32402. }
  32403. }
  32404. this._fillAlignment(size);
  32405. this._uniformSizes[name] = size;
  32406. this._uniformLocations[name] = this._uniformLocationPointer;
  32407. this._uniformLocationPointer += size;
  32408. for (var i = 0; i < size; i++) {
  32409. this._data.push(data[i]);
  32410. }
  32411. this._needSync = true;
  32412. };
  32413. /**
  32414. * Wrapper for addUniform.
  32415. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32416. * @param {Matrix} mat A 4x4 matrix.
  32417. */
  32418. UniformBuffer.prototype.addMatrix = function (name, mat) {
  32419. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  32420. };
  32421. /**
  32422. * Wrapper for addUniform.
  32423. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32424. * @param {number} x
  32425. * @param {number} y
  32426. */
  32427. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  32428. var temp = [x, y];
  32429. this.addUniform(name, temp);
  32430. };
  32431. /**
  32432. * Wrapper for addUniform.
  32433. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32434. * @param {number} x
  32435. * @param {number} y
  32436. * @param {number} z
  32437. */
  32438. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  32439. var temp = [x, y, z];
  32440. this.addUniform(name, temp);
  32441. };
  32442. /**
  32443. * Wrapper for addUniform.
  32444. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32445. * @param {Color3} color
  32446. */
  32447. UniformBuffer.prototype.addColor3 = function (name, color) {
  32448. var temp = new Array();
  32449. color.toArray(temp);
  32450. this.addUniform(name, temp);
  32451. };
  32452. /**
  32453. * Wrapper for addUniform.
  32454. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32455. * @param {Color3} color
  32456. * @param {number} alpha
  32457. */
  32458. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  32459. var temp = new Array();
  32460. color.toArray(temp);
  32461. temp.push(alpha);
  32462. this.addUniform(name, temp);
  32463. };
  32464. /**
  32465. * Wrapper for addUniform.
  32466. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32467. * @param {Vector3} vector
  32468. */
  32469. UniformBuffer.prototype.addVector3 = function (name, vector) {
  32470. var temp = new Array();
  32471. vector.toArray(temp);
  32472. this.addUniform(name, temp);
  32473. };
  32474. /**
  32475. * Wrapper for addUniform.
  32476. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32477. */
  32478. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  32479. this.addUniform(name, 12);
  32480. };
  32481. /**
  32482. * Wrapper for addUniform.
  32483. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32484. */
  32485. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  32486. this.addUniform(name, 8);
  32487. };
  32488. /**
  32489. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  32490. */
  32491. UniformBuffer.prototype.create = function () {
  32492. if (this._noUBO) {
  32493. return;
  32494. }
  32495. if (this._buffer) {
  32496. return; // nothing to do
  32497. }
  32498. // See spec, alignment must be filled as a vec4
  32499. this._fillAlignment(4);
  32500. this._bufferData = new Float32Array(this._data);
  32501. this._rebuild();
  32502. this._needSync = true;
  32503. };
  32504. UniformBuffer.prototype._rebuild = function () {
  32505. if (this._noUBO) {
  32506. return;
  32507. }
  32508. if (this._dynamic) {
  32509. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32510. }
  32511. else {
  32512. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32513. }
  32514. };
  32515. /**
  32516. * Updates the WebGL Uniform Buffer on the GPU.
  32517. * If the `dynamic` flag is set to true, no cache comparison is done.
  32518. * Otherwise, the buffer will be updated only if the cache differs.
  32519. */
  32520. UniformBuffer.prototype.update = function () {
  32521. if (!this._buffer) {
  32522. this.create();
  32523. return;
  32524. }
  32525. if (!this._dynamic && !this._needSync) {
  32526. return;
  32527. }
  32528. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32529. this._needSync = false;
  32530. };
  32531. /**
  32532. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32533. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32534. * @param {number[]|Float32Array} data Flattened data
  32535. * @param {number} size Size of the data.
  32536. */
  32537. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32538. var location = this._uniformLocations[uniformName];
  32539. if (location === undefined) {
  32540. if (this._buffer) {
  32541. // Cannot add an uniform if the buffer is already created
  32542. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32543. return;
  32544. }
  32545. this.addUniform(uniformName, size);
  32546. location = this._uniformLocations[uniformName];
  32547. }
  32548. if (!this._buffer) {
  32549. this.create();
  32550. }
  32551. if (!this._dynamic) {
  32552. // Cache for static uniform buffers
  32553. var changed = false;
  32554. for (var i = 0; i < size; i++) {
  32555. if (this._bufferData[location + i] !== data[i]) {
  32556. changed = true;
  32557. this._bufferData[location + i] = data[i];
  32558. }
  32559. }
  32560. this._needSync = this._needSync || changed;
  32561. }
  32562. else {
  32563. // No cache for dynamic
  32564. for (var i = 0; i < size; i++) {
  32565. this._bufferData[location + i] = data[i];
  32566. }
  32567. }
  32568. };
  32569. // Update methods
  32570. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32571. // To match std140, matrix must be realigned
  32572. for (var i = 0; i < 3; i++) {
  32573. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32574. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32575. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32576. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32577. }
  32578. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32579. };
  32580. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32581. this._currentEffect.setMatrix3x3(name, matrix);
  32582. };
  32583. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32584. this._currentEffect.setMatrix2x2(name, matrix);
  32585. };
  32586. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32587. // To match std140, matrix must be realigned
  32588. for (var i = 0; i < 2; i++) {
  32589. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32590. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32591. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32592. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32593. }
  32594. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32595. };
  32596. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32597. this._currentEffect.setFloat(name, x);
  32598. };
  32599. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32600. UniformBuffer._tempBuffer[0] = x;
  32601. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32602. };
  32603. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32604. if (suffix === void 0) { suffix = ""; }
  32605. this._currentEffect.setFloat2(name + suffix, x, y);
  32606. };
  32607. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32608. if (suffix === void 0) { suffix = ""; }
  32609. UniformBuffer._tempBuffer[0] = x;
  32610. UniformBuffer._tempBuffer[1] = y;
  32611. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32612. };
  32613. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32614. if (suffix === void 0) { suffix = ""; }
  32615. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32616. };
  32617. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32618. if (suffix === void 0) { suffix = ""; }
  32619. UniformBuffer._tempBuffer[0] = x;
  32620. UniformBuffer._tempBuffer[1] = y;
  32621. UniformBuffer._tempBuffer[2] = z;
  32622. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32623. };
  32624. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32625. if (suffix === void 0) { suffix = ""; }
  32626. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32627. };
  32628. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32629. if (suffix === void 0) { suffix = ""; }
  32630. UniformBuffer._tempBuffer[0] = x;
  32631. UniformBuffer._tempBuffer[1] = y;
  32632. UniformBuffer._tempBuffer[2] = z;
  32633. UniformBuffer._tempBuffer[3] = w;
  32634. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32635. };
  32636. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32637. this._currentEffect.setMatrix(name, mat);
  32638. };
  32639. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32640. this.updateUniform(name, mat.toArray(), 16);
  32641. };
  32642. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32643. this._currentEffect.setVector3(name, vector);
  32644. };
  32645. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32646. vector.toArray(UniformBuffer._tempBuffer);
  32647. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32648. };
  32649. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32650. this._currentEffect.setVector4(name, vector);
  32651. };
  32652. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32653. vector.toArray(UniformBuffer._tempBuffer);
  32654. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32655. };
  32656. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32657. if (suffix === void 0) { suffix = ""; }
  32658. this._currentEffect.setColor3(name + suffix, color);
  32659. };
  32660. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32661. if (suffix === void 0) { suffix = ""; }
  32662. color.toArray(UniformBuffer._tempBuffer);
  32663. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32664. };
  32665. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32666. if (suffix === void 0) { suffix = ""; }
  32667. this._currentEffect.setColor4(name + suffix, color, alpha);
  32668. };
  32669. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32670. if (suffix === void 0) { suffix = ""; }
  32671. color.toArray(UniformBuffer._tempBuffer);
  32672. UniformBuffer._tempBuffer[3] = alpha;
  32673. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32674. };
  32675. /**
  32676. * Sets a sampler uniform on the effect.
  32677. * @param {string} name Name of the sampler.
  32678. * @param {Texture} texture
  32679. */
  32680. UniformBuffer.prototype.setTexture = function (name, texture) {
  32681. this._currentEffect.setTexture(name, texture);
  32682. };
  32683. /**
  32684. * Directly updates the value of the uniform in the cache AND on the GPU.
  32685. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32686. * @param {number[]|Float32Array} data Flattened data
  32687. */
  32688. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32689. this.updateUniform(uniformName, data, data.length);
  32690. this.update();
  32691. };
  32692. /**
  32693. * Binds this uniform buffer to an effect.
  32694. * @param {Effect} effect
  32695. * @param {string} name Name of the uniform block in the shader.
  32696. */
  32697. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32698. this._currentEffect = effect;
  32699. if (this._noUBO || !this._buffer) {
  32700. return;
  32701. }
  32702. effect.bindUniformBuffer(this._buffer, name);
  32703. };
  32704. /**
  32705. * Disposes the uniform buffer.
  32706. */
  32707. UniformBuffer.prototype.dispose = function () {
  32708. if (this._noUBO) {
  32709. return;
  32710. }
  32711. var index = this._engine._uniformBuffers.indexOf(this);
  32712. if (index !== -1) {
  32713. this._engine._uniformBuffers.splice(index, 1);
  32714. }
  32715. if (!this._buffer) {
  32716. return;
  32717. }
  32718. if (this._engine._releaseBuffer(this._buffer)) {
  32719. this._buffer = null;
  32720. }
  32721. };
  32722. // Pool for avoiding memory leaks
  32723. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32724. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32725. return UniformBuffer;
  32726. }());
  32727. BABYLON.UniformBuffer = UniformBuffer;
  32728. })(BABYLON || (BABYLON = {}));
  32729. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32730. var BABYLON;
  32731. (function (BABYLON) {
  32732. var VertexData = /** @class */ (function () {
  32733. function VertexData() {
  32734. }
  32735. VertexData.prototype.set = function (data, kind) {
  32736. switch (kind) {
  32737. case BABYLON.VertexBuffer.PositionKind:
  32738. this.positions = data;
  32739. break;
  32740. case BABYLON.VertexBuffer.NormalKind:
  32741. this.normals = data;
  32742. break;
  32743. case BABYLON.VertexBuffer.TangentKind:
  32744. this.tangents = data;
  32745. break;
  32746. case BABYLON.VertexBuffer.UVKind:
  32747. this.uvs = data;
  32748. break;
  32749. case BABYLON.VertexBuffer.UV2Kind:
  32750. this.uvs2 = data;
  32751. break;
  32752. case BABYLON.VertexBuffer.UV3Kind:
  32753. this.uvs3 = data;
  32754. break;
  32755. case BABYLON.VertexBuffer.UV4Kind:
  32756. this.uvs4 = data;
  32757. break;
  32758. case BABYLON.VertexBuffer.UV5Kind:
  32759. this.uvs5 = data;
  32760. break;
  32761. case BABYLON.VertexBuffer.UV6Kind:
  32762. this.uvs6 = data;
  32763. break;
  32764. case BABYLON.VertexBuffer.ColorKind:
  32765. this.colors = data;
  32766. break;
  32767. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32768. this.matricesIndices = data;
  32769. break;
  32770. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32771. this.matricesWeights = data;
  32772. break;
  32773. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32774. this.matricesIndicesExtra = data;
  32775. break;
  32776. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32777. this.matricesWeightsExtra = data;
  32778. break;
  32779. }
  32780. };
  32781. /**
  32782. * Associates the vertexData to the passed Mesh.
  32783. * Sets it as updatable or not (default `false`).
  32784. * Returns the VertexData.
  32785. */
  32786. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32787. this._applyTo(mesh, updatable);
  32788. return this;
  32789. };
  32790. /**
  32791. * Associates the vertexData to the passed Geometry.
  32792. * Sets it as updatable or not (default `false`).
  32793. * Returns the VertexData.
  32794. */
  32795. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32796. this._applyTo(geometry, updatable);
  32797. return this;
  32798. };
  32799. /**
  32800. * Updates the associated mesh.
  32801. * Returns the VertexData.
  32802. */
  32803. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32804. this._update(mesh);
  32805. return this;
  32806. };
  32807. /**
  32808. * Updates the associated geometry.
  32809. * Returns the VertexData.
  32810. */
  32811. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32812. this._update(geometry);
  32813. return this;
  32814. };
  32815. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32816. if (updatable === void 0) { updatable = false; }
  32817. if (this.positions) {
  32818. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32819. }
  32820. if (this.normals) {
  32821. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32822. }
  32823. if (this.tangents) {
  32824. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  32825. }
  32826. if (this.uvs) {
  32827. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32828. }
  32829. if (this.uvs2) {
  32830. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32831. }
  32832. if (this.uvs3) {
  32833. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32834. }
  32835. if (this.uvs4) {
  32836. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32837. }
  32838. if (this.uvs5) {
  32839. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32840. }
  32841. if (this.uvs6) {
  32842. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32843. }
  32844. if (this.colors) {
  32845. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32846. }
  32847. if (this.matricesIndices) {
  32848. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32849. }
  32850. if (this.matricesWeights) {
  32851. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32852. }
  32853. if (this.matricesIndicesExtra) {
  32854. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32855. }
  32856. if (this.matricesWeightsExtra) {
  32857. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32858. }
  32859. if (this.indices) {
  32860. meshOrGeometry.setIndices(this.indices, null, updatable);
  32861. }
  32862. return this;
  32863. };
  32864. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32865. if (this.positions) {
  32866. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32867. }
  32868. if (this.normals) {
  32869. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32870. }
  32871. if (this.tangents) {
  32872. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  32873. }
  32874. if (this.uvs) {
  32875. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32876. }
  32877. if (this.uvs2) {
  32878. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32879. }
  32880. if (this.uvs3) {
  32881. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32882. }
  32883. if (this.uvs4) {
  32884. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32885. }
  32886. if (this.uvs5) {
  32887. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32888. }
  32889. if (this.uvs6) {
  32890. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32891. }
  32892. if (this.colors) {
  32893. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32894. }
  32895. if (this.matricesIndices) {
  32896. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32897. }
  32898. if (this.matricesWeights) {
  32899. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32900. }
  32901. if (this.matricesIndicesExtra) {
  32902. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32903. }
  32904. if (this.matricesWeightsExtra) {
  32905. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32906. }
  32907. if (this.indices) {
  32908. meshOrGeometry.setIndices(this.indices, null);
  32909. }
  32910. return this;
  32911. };
  32912. /**
  32913. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  32914. * Returns the VertexData.
  32915. */
  32916. VertexData.prototype.transform = function (matrix) {
  32917. var transformed = BABYLON.Vector3.Zero();
  32918. var index;
  32919. if (this.positions) {
  32920. var position = BABYLON.Vector3.Zero();
  32921. for (index = 0; index < this.positions.length; index += 3) {
  32922. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  32923. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  32924. this.positions[index] = transformed.x;
  32925. this.positions[index + 1] = transformed.y;
  32926. this.positions[index + 2] = transformed.z;
  32927. }
  32928. }
  32929. if (this.normals) {
  32930. var normal = BABYLON.Vector3.Zero();
  32931. for (index = 0; index < this.normals.length; index += 3) {
  32932. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  32933. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  32934. this.normals[index] = transformed.x;
  32935. this.normals[index + 1] = transformed.y;
  32936. this.normals[index + 2] = transformed.z;
  32937. }
  32938. }
  32939. if (this.tangents) {
  32940. var tangent = BABYLON.Vector4.Zero();
  32941. var tangentTransformed = BABYLON.Vector4.Zero();
  32942. for (index = 0; index < this.tangents.length; index += 4) {
  32943. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  32944. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  32945. this.tangents[index] = tangentTransformed.x;
  32946. this.tangents[index + 1] = tangentTransformed.y;
  32947. this.tangents[index + 2] = tangentTransformed.z;
  32948. this.tangents[index + 3] = tangentTransformed.w;
  32949. }
  32950. }
  32951. return this;
  32952. };
  32953. /**
  32954. * Merges the passed VertexData into the current one.
  32955. * Returns the modified VertexData.
  32956. */
  32957. VertexData.prototype.merge = function (other) {
  32958. this._validate();
  32959. other._validate();
  32960. if (!this.normals !== !other.normals ||
  32961. !this.tangents !== !other.tangents ||
  32962. !this.uvs !== !other.uvs ||
  32963. !this.uvs2 !== !other.uvs2 ||
  32964. !this.uvs3 !== !other.uvs3 ||
  32965. !this.uvs4 !== !other.uvs4 ||
  32966. !this.uvs5 !== !other.uvs5 ||
  32967. !this.uvs6 !== !other.uvs6 ||
  32968. !this.colors !== !other.colors ||
  32969. !this.matricesIndices !== !other.matricesIndices ||
  32970. !this.matricesWeights !== !other.matricesWeights ||
  32971. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  32972. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  32973. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  32974. }
  32975. if (other.indices) {
  32976. if (!this.indices) {
  32977. this.indices = [];
  32978. }
  32979. var offset = this.positions ? this.positions.length / 3 : 0;
  32980. for (var index = 0; index < other.indices.length; index++) {
  32981. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  32982. this.indices.push(other.indices[index] + offset);
  32983. }
  32984. }
  32985. this.positions = this._mergeElement(this.positions, other.positions);
  32986. this.normals = this._mergeElement(this.normals, other.normals);
  32987. this.tangents = this._mergeElement(this.tangents, other.tangents);
  32988. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32989. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32990. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32991. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32992. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32993. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32994. this.colors = this._mergeElement(this.colors, other.colors);
  32995. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32996. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32997. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32998. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32999. return this;
  33000. };
  33001. VertexData.prototype._mergeElement = function (source, other) {
  33002. if (!source) {
  33003. return other;
  33004. }
  33005. if (!other) {
  33006. return source;
  33007. }
  33008. var len = other.length + source.length;
  33009. var isSrcTypedArray = source instanceof Float32Array;
  33010. var isOthTypedArray = other instanceof Float32Array;
  33011. // use non-loop method when the source is Float32Array
  33012. if (isSrcTypedArray) {
  33013. var ret32 = new Float32Array(len);
  33014. ret32.set(source);
  33015. ret32.set(other, source.length);
  33016. return ret32;
  33017. // source is number[], when other is also use concat
  33018. }
  33019. else if (!isOthTypedArray) {
  33020. return source.concat(other);
  33021. // source is a number[], but other is a Float32Array, loop required
  33022. }
  33023. else {
  33024. var ret = source.slice(0); // copy source to a separate array
  33025. for (var i = 0, len = other.length; i < len; i++) {
  33026. ret.push(other[i]);
  33027. }
  33028. return ret;
  33029. }
  33030. };
  33031. VertexData.prototype._validate = function () {
  33032. if (!this.positions) {
  33033. throw new Error("Positions are required");
  33034. }
  33035. var getElementCount = function (kind, values) {
  33036. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  33037. if ((values.length % stride) !== 0) {
  33038. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  33039. }
  33040. return values.length / stride;
  33041. };
  33042. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  33043. var validateElementCount = function (kind, values) {
  33044. var elementCount = getElementCount(kind, values);
  33045. if (elementCount !== positionsElementCount) {
  33046. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  33047. }
  33048. };
  33049. if (this.normals)
  33050. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  33051. if (this.tangents)
  33052. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  33053. if (this.uvs)
  33054. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  33055. if (this.uvs2)
  33056. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  33057. if (this.uvs3)
  33058. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  33059. if (this.uvs4)
  33060. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  33061. if (this.uvs5)
  33062. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  33063. if (this.uvs6)
  33064. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  33065. if (this.colors)
  33066. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  33067. if (this.matricesIndices)
  33068. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  33069. if (this.matricesWeights)
  33070. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  33071. if (this.matricesIndicesExtra)
  33072. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  33073. if (this.matricesWeightsExtra)
  33074. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  33075. };
  33076. /**
  33077. * Serializes the VertexData.
  33078. * Returns a serialized object.
  33079. */
  33080. VertexData.prototype.serialize = function () {
  33081. var serializationObject = this.serialize();
  33082. if (this.positions) {
  33083. serializationObject.positions = this.positions;
  33084. }
  33085. if (this.normals) {
  33086. serializationObject.normals = this.normals;
  33087. }
  33088. if (this.tangents) {
  33089. serializationObject.tangents = this.tangents;
  33090. }
  33091. if (this.uvs) {
  33092. serializationObject.uvs = this.uvs;
  33093. }
  33094. if (this.uvs2) {
  33095. serializationObject.uvs2 = this.uvs2;
  33096. }
  33097. if (this.uvs3) {
  33098. serializationObject.uvs3 = this.uvs3;
  33099. }
  33100. if (this.uvs4) {
  33101. serializationObject.uvs4 = this.uvs4;
  33102. }
  33103. if (this.uvs5) {
  33104. serializationObject.uvs5 = this.uvs5;
  33105. }
  33106. if (this.uvs6) {
  33107. serializationObject.uvs6 = this.uvs6;
  33108. }
  33109. if (this.colors) {
  33110. serializationObject.colors = this.colors;
  33111. }
  33112. if (this.matricesIndices) {
  33113. serializationObject.matricesIndices = this.matricesIndices;
  33114. serializationObject.matricesIndices._isExpanded = true;
  33115. }
  33116. if (this.matricesWeights) {
  33117. serializationObject.matricesWeights = this.matricesWeights;
  33118. }
  33119. if (this.matricesIndicesExtra) {
  33120. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  33121. serializationObject.matricesIndicesExtra._isExpanded = true;
  33122. }
  33123. if (this.matricesWeightsExtra) {
  33124. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  33125. }
  33126. serializationObject.indices = this.indices;
  33127. return serializationObject;
  33128. };
  33129. // Statics
  33130. /**
  33131. * Returns the object VertexData associated to the passed mesh.
  33132. */
  33133. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  33134. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  33135. };
  33136. /**
  33137. * Returns the object VertexData associated to the passed geometry.
  33138. */
  33139. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  33140. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  33141. };
  33142. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  33143. var result = new VertexData();
  33144. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33145. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  33146. }
  33147. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33148. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  33149. }
  33150. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  33151. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  33152. }
  33153. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33154. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  33155. }
  33156. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33157. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  33158. }
  33159. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33160. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  33161. }
  33162. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33163. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  33164. }
  33165. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33166. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  33167. }
  33168. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33169. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  33170. }
  33171. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33172. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  33173. }
  33174. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33175. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  33176. }
  33177. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33178. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  33179. }
  33180. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  33181. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  33182. }
  33183. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  33184. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  33185. }
  33186. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  33187. return result;
  33188. };
  33189. /**
  33190. * Creates the vertexData of the Ribbon.
  33191. */
  33192. VertexData.CreateRibbon = function (options) {
  33193. var pathArray = options.pathArray;
  33194. var closeArray = options.closeArray || false;
  33195. var closePath = options.closePath || false;
  33196. var invertUV = options.invertUV || false;
  33197. var defaultOffset = Math.floor(pathArray[0].length / 2);
  33198. var offset = options.offset || defaultOffset;
  33199. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  33200. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33201. var customUV = options.uvs;
  33202. var customColors = options.colors;
  33203. var positions = [];
  33204. var indices = [];
  33205. var normals = [];
  33206. var uvs = [];
  33207. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  33208. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  33209. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  33210. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  33211. var minlg; // minimal length among all paths from pathArray
  33212. var lg = []; // array of path lengths : nb of vertex per path
  33213. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  33214. var p; // path iterator
  33215. var i; // point iterator
  33216. var j; // point iterator
  33217. // if single path in pathArray
  33218. if (pathArray.length < 2) {
  33219. var ar1 = [];
  33220. var ar2 = [];
  33221. for (i = 0; i < pathArray[0].length - offset; i++) {
  33222. ar1.push(pathArray[0][i]);
  33223. ar2.push(pathArray[0][i + offset]);
  33224. }
  33225. pathArray = [ar1, ar2];
  33226. }
  33227. // positions and horizontal distances (u)
  33228. var idc = 0;
  33229. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  33230. var path;
  33231. var l;
  33232. minlg = pathArray[0].length;
  33233. var vectlg;
  33234. var dist;
  33235. for (p = 0; p < pathArray.length; p++) {
  33236. uTotalDistance[p] = 0;
  33237. us[p] = [0];
  33238. path = pathArray[p];
  33239. l = path.length;
  33240. minlg = (minlg < l) ? minlg : l;
  33241. j = 0;
  33242. while (j < l) {
  33243. positions.push(path[j].x, path[j].y, path[j].z);
  33244. if (j > 0) {
  33245. vectlg = path[j].subtract(path[j - 1]).length();
  33246. dist = vectlg + uTotalDistance[p];
  33247. us[p].push(dist);
  33248. uTotalDistance[p] = dist;
  33249. }
  33250. j++;
  33251. }
  33252. if (closePath) {
  33253. j--;
  33254. positions.push(path[0].x, path[0].y, path[0].z);
  33255. vectlg = path[j].subtract(path[0]).length();
  33256. dist = vectlg + uTotalDistance[p];
  33257. us[p].push(dist);
  33258. uTotalDistance[p] = dist;
  33259. }
  33260. lg[p] = l + closePathCorr;
  33261. idx[p] = idc;
  33262. idc += (l + closePathCorr);
  33263. }
  33264. // vertical distances (v)
  33265. var path1;
  33266. var path2;
  33267. var vertex1 = null;
  33268. var vertex2 = null;
  33269. for (i = 0; i < minlg + closePathCorr; i++) {
  33270. vTotalDistance[i] = 0;
  33271. vs[i] = [0];
  33272. for (p = 0; p < pathArray.length - 1; p++) {
  33273. path1 = pathArray[p];
  33274. path2 = pathArray[p + 1];
  33275. if (i === minlg) {
  33276. vertex1 = path1[0];
  33277. vertex2 = path2[0];
  33278. }
  33279. else {
  33280. vertex1 = path1[i];
  33281. vertex2 = path2[i];
  33282. }
  33283. vectlg = vertex2.subtract(vertex1).length();
  33284. dist = vectlg + vTotalDistance[i];
  33285. vs[i].push(dist);
  33286. vTotalDistance[i] = dist;
  33287. }
  33288. if (closeArray && vertex2 && vertex1) {
  33289. path1 = pathArray[p];
  33290. path2 = pathArray[0];
  33291. if (i === minlg) {
  33292. vertex2 = path2[0];
  33293. }
  33294. vectlg = vertex2.subtract(vertex1).length();
  33295. dist = vectlg + vTotalDistance[i];
  33296. vTotalDistance[i] = dist;
  33297. }
  33298. }
  33299. // uvs
  33300. var u;
  33301. var v;
  33302. if (customUV) {
  33303. for (p = 0; p < customUV.length; p++) {
  33304. uvs.push(customUV[p].x, customUV[p].y);
  33305. }
  33306. }
  33307. else {
  33308. for (p = 0; p < pathArray.length; p++) {
  33309. for (i = 0; i < minlg + closePathCorr; i++) {
  33310. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  33311. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  33312. if (invertUV) {
  33313. uvs.push(v, u);
  33314. }
  33315. else {
  33316. uvs.push(u, v);
  33317. }
  33318. }
  33319. }
  33320. }
  33321. // indices
  33322. p = 0; // path index
  33323. var pi = 0; // positions array index
  33324. var l1 = lg[p] - 1; // path1 length
  33325. var l2 = lg[p + 1] - 1; // path2 length
  33326. var min = (l1 < l2) ? l1 : l2; // current path stop index
  33327. var shft = idx[1] - idx[0]; // shift
  33328. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  33329. while (pi <= min && p < path1nb) {
  33330. // 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
  33331. indices.push(pi, pi + shft, pi + 1);
  33332. indices.push(pi + shft + 1, pi + 1, pi + shft);
  33333. pi += 1;
  33334. if (pi === min) {
  33335. p++;
  33336. if (p === lg.length - 1) {
  33337. shft = idx[0] - idx[p];
  33338. l1 = lg[p] - 1;
  33339. l2 = lg[0] - 1;
  33340. }
  33341. else {
  33342. shft = idx[p + 1] - idx[p];
  33343. l1 = lg[p] - 1;
  33344. l2 = lg[p + 1] - 1;
  33345. }
  33346. pi = idx[p];
  33347. min = (l1 < l2) ? l1 + pi : l2 + pi;
  33348. }
  33349. }
  33350. // normals
  33351. VertexData.ComputeNormals(positions, indices, normals);
  33352. if (closePath) {
  33353. var indexFirst = 0;
  33354. var indexLast = 0;
  33355. for (p = 0; p < pathArray.length; p++) {
  33356. indexFirst = idx[p] * 3;
  33357. if (p + 1 < pathArray.length) {
  33358. indexLast = (idx[p + 1] - 1) * 3;
  33359. }
  33360. else {
  33361. indexLast = normals.length - 3;
  33362. }
  33363. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  33364. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  33365. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  33366. normals[indexLast] = normals[indexFirst];
  33367. normals[indexLast + 1] = normals[indexFirst + 1];
  33368. normals[indexLast + 2] = normals[indexFirst + 2];
  33369. }
  33370. }
  33371. // sides
  33372. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33373. // Colors
  33374. var colors = null;
  33375. if (customColors) {
  33376. colors = new Float32Array(customColors.length * 4);
  33377. for (var c = 0; c < customColors.length; c++) {
  33378. colors[c * 4] = customColors[c].r;
  33379. colors[c * 4 + 1] = customColors[c].g;
  33380. colors[c * 4 + 2] = customColors[c].b;
  33381. colors[c * 4 + 3] = customColors[c].a;
  33382. }
  33383. }
  33384. // Result
  33385. var vertexData = new VertexData();
  33386. var positions32 = new Float32Array(positions);
  33387. var normals32 = new Float32Array(normals);
  33388. var uvs32 = new Float32Array(uvs);
  33389. vertexData.indices = indices;
  33390. vertexData.positions = positions32;
  33391. vertexData.normals = normals32;
  33392. vertexData.uvs = uvs32;
  33393. if (colors) {
  33394. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  33395. }
  33396. if (closePath) {
  33397. vertexData._idx = idx;
  33398. }
  33399. return vertexData;
  33400. };
  33401. /**
  33402. * Creates the VertexData of the Box.
  33403. */
  33404. VertexData.CreateBox = function (options) {
  33405. var normalsSource = [
  33406. new BABYLON.Vector3(0, 0, 1),
  33407. new BABYLON.Vector3(0, 0, -1),
  33408. new BABYLON.Vector3(1, 0, 0),
  33409. new BABYLON.Vector3(-1, 0, 0),
  33410. new BABYLON.Vector3(0, 1, 0),
  33411. new BABYLON.Vector3(0, -1, 0)
  33412. ];
  33413. var indices = [];
  33414. var positions = [];
  33415. var normals = [];
  33416. var uvs = [];
  33417. var width = options.width || options.size || 1;
  33418. var height = options.height || options.size || 1;
  33419. var depth = options.depth || options.size || 1;
  33420. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33421. var faceUV = options.faceUV || new Array(6);
  33422. var faceColors = options.faceColors;
  33423. var colors = [];
  33424. // default face colors and UV if undefined
  33425. for (var f = 0; f < 6; f++) {
  33426. if (faceUV[f] === undefined) {
  33427. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33428. }
  33429. if (faceColors && faceColors[f] === undefined) {
  33430. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33431. }
  33432. }
  33433. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33434. // Create each face in turn.
  33435. for (var index = 0; index < normalsSource.length; index++) {
  33436. var normal = normalsSource[index];
  33437. // Get two vectors perpendicular to the face normal and to each other.
  33438. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33439. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33440. // Six indices (two triangles) per face.
  33441. var verticesLength = positions.length / 3;
  33442. indices.push(verticesLength);
  33443. indices.push(verticesLength + 1);
  33444. indices.push(verticesLength + 2);
  33445. indices.push(verticesLength);
  33446. indices.push(verticesLength + 2);
  33447. indices.push(verticesLength + 3);
  33448. // Four vertices per face.
  33449. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33450. positions.push(vertex.x, vertex.y, vertex.z);
  33451. normals.push(normal.x, normal.y, normal.z);
  33452. uvs.push(faceUV[index].z, faceUV[index].w);
  33453. if (faceColors) {
  33454. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33455. }
  33456. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33457. positions.push(vertex.x, vertex.y, vertex.z);
  33458. normals.push(normal.x, normal.y, normal.z);
  33459. uvs.push(faceUV[index].x, faceUV[index].w);
  33460. if (faceColors) {
  33461. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33462. }
  33463. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33464. positions.push(vertex.x, vertex.y, vertex.z);
  33465. normals.push(normal.x, normal.y, normal.z);
  33466. uvs.push(faceUV[index].x, faceUV[index].y);
  33467. if (faceColors) {
  33468. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33469. }
  33470. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33471. positions.push(vertex.x, vertex.y, vertex.z);
  33472. normals.push(normal.x, normal.y, normal.z);
  33473. uvs.push(faceUV[index].z, faceUV[index].y);
  33474. if (faceColors) {
  33475. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33476. }
  33477. }
  33478. // sides
  33479. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33480. // Result
  33481. var vertexData = new VertexData();
  33482. vertexData.indices = indices;
  33483. vertexData.positions = positions;
  33484. vertexData.normals = normals;
  33485. vertexData.uvs = uvs;
  33486. if (faceColors) {
  33487. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33488. vertexData.colors = totalColors;
  33489. }
  33490. return vertexData;
  33491. };
  33492. /**
  33493. * Creates the VertexData of the Sphere.
  33494. */
  33495. VertexData.CreateSphere = function (options) {
  33496. var segments = options.segments || 32;
  33497. var diameterX = options.diameterX || options.diameter || 1;
  33498. var diameterY = options.diameterY || options.diameter || 1;
  33499. var diameterZ = options.diameterZ || options.diameter || 1;
  33500. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33501. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33502. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33503. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33504. var totalZRotationSteps = 2 + segments;
  33505. var totalYRotationSteps = 2 * totalZRotationSteps;
  33506. var indices = [];
  33507. var positions = [];
  33508. var normals = [];
  33509. var uvs = [];
  33510. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33511. var normalizedZ = zRotationStep / totalZRotationSteps;
  33512. var angleZ = normalizedZ * Math.PI * slice;
  33513. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33514. var normalizedY = yRotationStep / totalYRotationSteps;
  33515. var angleY = normalizedY * Math.PI * 2 * arc;
  33516. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33517. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33518. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33519. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33520. var vertex = complete.multiply(radius);
  33521. var normal = complete.divide(radius).normalize();
  33522. positions.push(vertex.x, vertex.y, vertex.z);
  33523. normals.push(normal.x, normal.y, normal.z);
  33524. uvs.push(normalizedY, normalizedZ);
  33525. }
  33526. if (zRotationStep > 0) {
  33527. var verticesCount = positions.length / 3;
  33528. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33529. indices.push((firstIndex));
  33530. indices.push((firstIndex + 1));
  33531. indices.push(firstIndex + totalYRotationSteps + 1);
  33532. indices.push((firstIndex + totalYRotationSteps + 1));
  33533. indices.push((firstIndex + 1));
  33534. indices.push((firstIndex + totalYRotationSteps + 2));
  33535. }
  33536. }
  33537. }
  33538. // Sides
  33539. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33540. // Result
  33541. var vertexData = new VertexData();
  33542. vertexData.indices = indices;
  33543. vertexData.positions = positions;
  33544. vertexData.normals = normals;
  33545. vertexData.uvs = uvs;
  33546. return vertexData;
  33547. };
  33548. /**
  33549. * Creates the VertexData of the Cylinder or Cone.
  33550. */
  33551. VertexData.CreateCylinder = function (options) {
  33552. var height = options.height || 2;
  33553. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33554. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33555. var tessellation = options.tessellation || 24;
  33556. var subdivisions = options.subdivisions || 1;
  33557. var hasRings = options.hasRings ? true : false;
  33558. var enclose = options.enclose ? true : false;
  33559. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33560. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33561. var faceUV = options.faceUV || new Array(3);
  33562. var faceColors = options.faceColors;
  33563. // default face colors and UV if undefined
  33564. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33565. var ringNb = (hasRings) ? subdivisions : 1;
  33566. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33567. var f;
  33568. for (f = 0; f < surfaceNb; f++) {
  33569. if (faceColors && faceColors[f] === undefined) {
  33570. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33571. }
  33572. }
  33573. for (f = 0; f < surfaceNb; f++) {
  33574. if (faceUV && faceUV[f] === undefined) {
  33575. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33576. }
  33577. }
  33578. var indices = new Array();
  33579. var positions = new Array();
  33580. var normals = new Array();
  33581. var uvs = new Array();
  33582. var colors = new Array();
  33583. var angle_step = Math.PI * 2 * arc / tessellation;
  33584. var angle;
  33585. var h;
  33586. var radius;
  33587. var tan = (diameterBottom - diameterTop) / 2 / height;
  33588. var ringVertex = BABYLON.Vector3.Zero();
  33589. var ringNormal = BABYLON.Vector3.Zero();
  33590. var ringFirstVertex = BABYLON.Vector3.Zero();
  33591. var ringFirstNormal = BABYLON.Vector3.Zero();
  33592. var quadNormal = BABYLON.Vector3.Zero();
  33593. var Y = BABYLON.Axis.Y;
  33594. // positions, normals, uvs
  33595. var i;
  33596. var j;
  33597. var r;
  33598. var ringIdx = 1;
  33599. var s = 1; // surface index
  33600. var cs = 0;
  33601. var v = 0;
  33602. for (i = 0; i <= subdivisions; i++) {
  33603. h = i / subdivisions;
  33604. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33605. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33606. for (r = 0; r < ringIdx; r++) {
  33607. if (hasRings) {
  33608. s += r;
  33609. }
  33610. if (enclose) {
  33611. s += 2 * r;
  33612. }
  33613. for (j = 0; j <= tessellation; j++) {
  33614. angle = j * angle_step;
  33615. // position
  33616. ringVertex.x = Math.cos(-angle) * radius;
  33617. ringVertex.y = -height / 2 + h * height;
  33618. ringVertex.z = Math.sin(-angle) * radius;
  33619. // normal
  33620. if (diameterTop === 0 && i === subdivisions) {
  33621. // if no top cap, reuse former normals
  33622. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33623. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33624. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33625. }
  33626. else {
  33627. ringNormal.x = ringVertex.x;
  33628. ringNormal.z = ringVertex.z;
  33629. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33630. ringNormal.normalize();
  33631. }
  33632. // keep first ring vertex values for enclose
  33633. if (j === 0) {
  33634. ringFirstVertex.copyFrom(ringVertex);
  33635. ringFirstNormal.copyFrom(ringNormal);
  33636. }
  33637. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33638. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33639. if (hasRings) {
  33640. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33641. }
  33642. else {
  33643. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33644. }
  33645. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33646. if (faceColors) {
  33647. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33648. }
  33649. }
  33650. // if enclose, add four vertices and their dedicated normals
  33651. if (arc !== 1 && enclose) {
  33652. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33653. positions.push(0, ringVertex.y, 0);
  33654. positions.push(0, ringVertex.y, 0);
  33655. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33656. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33657. quadNormal.normalize();
  33658. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33659. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33660. quadNormal.normalize();
  33661. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33662. if (hasRings) {
  33663. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33664. }
  33665. else {
  33666. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33667. }
  33668. uvs.push(faceUV[s + 1].x, v);
  33669. uvs.push(faceUV[s + 1].z, v);
  33670. if (hasRings) {
  33671. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33672. }
  33673. else {
  33674. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33675. }
  33676. uvs.push(faceUV[s + 2].x, v);
  33677. uvs.push(faceUV[s + 2].z, v);
  33678. if (faceColors) {
  33679. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33680. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33681. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33682. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33683. }
  33684. }
  33685. if (cs !== s) {
  33686. cs = s;
  33687. }
  33688. }
  33689. }
  33690. // indices
  33691. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33692. var s;
  33693. i = 0;
  33694. for (s = 0; s < subdivisions; s++) {
  33695. var i0 = 0;
  33696. var i1 = 0;
  33697. var i2 = 0;
  33698. var i3 = 0;
  33699. for (j = 0; j < tessellation; j++) {
  33700. i0 = i * (e + 1) + j;
  33701. i1 = (i + 1) * (e + 1) + j;
  33702. i2 = i * (e + 1) + (j + 1);
  33703. i3 = (i + 1) * (e + 1) + (j + 1);
  33704. indices.push(i0, i1, i2);
  33705. indices.push(i3, i2, i1);
  33706. }
  33707. if (arc !== 1 && enclose) {
  33708. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33709. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33710. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33711. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33712. }
  33713. i = (hasRings) ? (i + 2) : (i + 1);
  33714. }
  33715. // Caps
  33716. var createCylinderCap = function (isTop) {
  33717. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33718. if (radius === 0) {
  33719. return;
  33720. }
  33721. // Cap positions, normals & uvs
  33722. var angle;
  33723. var circleVector;
  33724. var i;
  33725. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33726. var c = null;
  33727. if (faceColors) {
  33728. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33729. }
  33730. // cap center
  33731. var vbase = positions.length / 3;
  33732. var offset = isTop ? height / 2 : -height / 2;
  33733. var center = new BABYLON.Vector3(0, offset, 0);
  33734. positions.push(center.x, center.y, center.z);
  33735. normals.push(0, isTop ? 1 : -1, 0);
  33736. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33737. if (c) {
  33738. colors.push(c.r, c.g, c.b, c.a);
  33739. }
  33740. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33741. for (i = 0; i <= tessellation; i++) {
  33742. angle = Math.PI * 2 * i * arc / tessellation;
  33743. var cos = Math.cos(-angle);
  33744. var sin = Math.sin(-angle);
  33745. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33746. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33747. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33748. normals.push(0, isTop ? 1 : -1, 0);
  33749. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33750. if (c) {
  33751. colors.push(c.r, c.g, c.b, c.a);
  33752. }
  33753. }
  33754. // Cap indices
  33755. for (i = 0; i < tessellation; i++) {
  33756. if (!isTop) {
  33757. indices.push(vbase);
  33758. indices.push(vbase + (i + 1));
  33759. indices.push(vbase + (i + 2));
  33760. }
  33761. else {
  33762. indices.push(vbase);
  33763. indices.push(vbase + (i + 2));
  33764. indices.push(vbase + (i + 1));
  33765. }
  33766. }
  33767. };
  33768. // add caps to geometry
  33769. createCylinderCap(false);
  33770. createCylinderCap(true);
  33771. // Sides
  33772. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33773. var vertexData = new VertexData();
  33774. vertexData.indices = indices;
  33775. vertexData.positions = positions;
  33776. vertexData.normals = normals;
  33777. vertexData.uvs = uvs;
  33778. if (faceColors) {
  33779. vertexData.colors = colors;
  33780. }
  33781. return vertexData;
  33782. };
  33783. /**
  33784. * Creates the VertexData of the Torus.
  33785. */
  33786. VertexData.CreateTorus = function (options) {
  33787. var indices = [];
  33788. var positions = [];
  33789. var normals = [];
  33790. var uvs = [];
  33791. var diameter = options.diameter || 1;
  33792. var thickness = options.thickness || 0.5;
  33793. var tessellation = options.tessellation || 16;
  33794. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33795. var stride = tessellation + 1;
  33796. for (var i = 0; i <= tessellation; i++) {
  33797. var u = i / tessellation;
  33798. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33799. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33800. for (var j = 0; j <= tessellation; j++) {
  33801. var v = 1 - j / tessellation;
  33802. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33803. var dx = Math.cos(innerAngle);
  33804. var dy = Math.sin(innerAngle);
  33805. // Create a vertex.
  33806. var normal = new BABYLON.Vector3(dx, dy, 0);
  33807. var position = normal.scale(thickness / 2);
  33808. var textureCoordinate = new BABYLON.Vector2(u, v);
  33809. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33810. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33811. positions.push(position.x, position.y, position.z);
  33812. normals.push(normal.x, normal.y, normal.z);
  33813. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33814. // And create indices for two triangles.
  33815. var nextI = (i + 1) % stride;
  33816. var nextJ = (j + 1) % stride;
  33817. indices.push(i * stride + j);
  33818. indices.push(i * stride + nextJ);
  33819. indices.push(nextI * stride + j);
  33820. indices.push(i * stride + nextJ);
  33821. indices.push(nextI * stride + nextJ);
  33822. indices.push(nextI * stride + j);
  33823. }
  33824. }
  33825. // Sides
  33826. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33827. // Result
  33828. var vertexData = new VertexData();
  33829. vertexData.indices = indices;
  33830. vertexData.positions = positions;
  33831. vertexData.normals = normals;
  33832. vertexData.uvs = uvs;
  33833. return vertexData;
  33834. };
  33835. /**
  33836. * Creates the VertexData of the LineSystem.
  33837. */
  33838. VertexData.CreateLineSystem = function (options) {
  33839. var indices = [];
  33840. var positions = [];
  33841. var lines = options.lines;
  33842. var colors = options.colors;
  33843. var vertexColors = [];
  33844. var idx = 0;
  33845. for (var l = 0; l < lines.length; l++) {
  33846. var points = lines[l];
  33847. for (var index = 0; index < points.length; index++) {
  33848. positions.push(points[index].x, points[index].y, points[index].z);
  33849. if (colors) {
  33850. var color = colors[l];
  33851. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  33852. }
  33853. if (index > 0) {
  33854. indices.push(idx - 1);
  33855. indices.push(idx);
  33856. }
  33857. idx++;
  33858. }
  33859. }
  33860. var vertexData = new VertexData();
  33861. vertexData.indices = indices;
  33862. vertexData.positions = positions;
  33863. if (colors) {
  33864. vertexData.colors = vertexColors;
  33865. }
  33866. return vertexData;
  33867. };
  33868. /**
  33869. * Create the VertexData of the DashedLines.
  33870. */
  33871. VertexData.CreateDashedLines = function (options) {
  33872. var dashSize = options.dashSize || 3;
  33873. var gapSize = options.gapSize || 1;
  33874. var dashNb = options.dashNb || 200;
  33875. var points = options.points;
  33876. var positions = new Array();
  33877. var indices = new Array();
  33878. var curvect = BABYLON.Vector3.Zero();
  33879. var lg = 0;
  33880. var nb = 0;
  33881. var shft = 0;
  33882. var dashshft = 0;
  33883. var curshft = 0;
  33884. var idx = 0;
  33885. var i = 0;
  33886. for (i = 0; i < points.length - 1; i++) {
  33887. points[i + 1].subtractToRef(points[i], curvect);
  33888. lg += curvect.length();
  33889. }
  33890. shft = lg / dashNb;
  33891. dashshft = dashSize * shft / (dashSize + gapSize);
  33892. for (i = 0; i < points.length - 1; i++) {
  33893. points[i + 1].subtractToRef(points[i], curvect);
  33894. nb = Math.floor(curvect.length() / shft);
  33895. curvect.normalize();
  33896. for (var j = 0; j < nb; j++) {
  33897. curshft = shft * j;
  33898. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  33899. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  33900. indices.push(idx, idx + 1);
  33901. idx += 2;
  33902. }
  33903. }
  33904. // Result
  33905. var vertexData = new VertexData();
  33906. vertexData.positions = positions;
  33907. vertexData.indices = indices;
  33908. return vertexData;
  33909. };
  33910. /**
  33911. * Creates the VertexData of the Ground.
  33912. */
  33913. VertexData.CreateGround = function (options) {
  33914. var indices = [];
  33915. var positions = [];
  33916. var normals = [];
  33917. var uvs = [];
  33918. var row, col;
  33919. var width = options.width || 1;
  33920. var height = options.height || 1;
  33921. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  33922. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  33923. for (row = 0; row <= subdivisionsY; row++) {
  33924. for (col = 0; col <= subdivisionsX; col++) {
  33925. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  33926. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33927. positions.push(position.x, position.y, position.z);
  33928. normals.push(normal.x, normal.y, normal.z);
  33929. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  33930. }
  33931. }
  33932. for (row = 0; row < subdivisionsY; row++) {
  33933. for (col = 0; col < subdivisionsX; col++) {
  33934. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33935. indices.push(col + 1 + row * (subdivisionsX + 1));
  33936. indices.push(col + row * (subdivisionsX + 1));
  33937. indices.push(col + (row + 1) * (subdivisionsX + 1));
  33938. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33939. indices.push(col + row * (subdivisionsX + 1));
  33940. }
  33941. }
  33942. // Result
  33943. var vertexData = new VertexData();
  33944. vertexData.indices = indices;
  33945. vertexData.positions = positions;
  33946. vertexData.normals = normals;
  33947. vertexData.uvs = uvs;
  33948. return vertexData;
  33949. };
  33950. /**
  33951. * Creates the VertexData of the TiledGround.
  33952. */
  33953. VertexData.CreateTiledGround = function (options) {
  33954. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  33955. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  33956. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  33957. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  33958. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  33959. var precision = options.precision || { w: 1, h: 1 };
  33960. var indices = new Array();
  33961. var positions = new Array();
  33962. var normals = new Array();
  33963. var uvs = new Array();
  33964. var row, col, tileRow, tileCol;
  33965. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  33966. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  33967. precision.w = (precision.w < 1) ? 1 : precision.w;
  33968. precision.h = (precision.h < 1) ? 1 : precision.h;
  33969. var tileSize = {
  33970. 'w': (xmax - xmin) / subdivisions.w,
  33971. 'h': (zmax - zmin) / subdivisions.h
  33972. };
  33973. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  33974. // Indices
  33975. var base = positions.length / 3;
  33976. var rowLength = precision.w + 1;
  33977. for (row = 0; row < precision.h; row++) {
  33978. for (col = 0; col < precision.w; col++) {
  33979. var square = [
  33980. base + col + row * rowLength,
  33981. base + (col + 1) + row * rowLength,
  33982. base + (col + 1) + (row + 1) * rowLength,
  33983. base + col + (row + 1) * rowLength
  33984. ];
  33985. indices.push(square[1]);
  33986. indices.push(square[2]);
  33987. indices.push(square[3]);
  33988. indices.push(square[0]);
  33989. indices.push(square[1]);
  33990. indices.push(square[3]);
  33991. }
  33992. }
  33993. // Position, normals and uvs
  33994. var position = BABYLON.Vector3.Zero();
  33995. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33996. for (row = 0; row <= precision.h; row++) {
  33997. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33998. for (col = 0; col <= precision.w; col++) {
  33999. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  34000. position.y = 0;
  34001. positions.push(position.x, position.y, position.z);
  34002. normals.push(normal.x, normal.y, normal.z);
  34003. uvs.push(col / precision.w, row / precision.h);
  34004. }
  34005. }
  34006. }
  34007. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  34008. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  34009. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  34010. }
  34011. }
  34012. // Result
  34013. var vertexData = new VertexData();
  34014. vertexData.indices = indices;
  34015. vertexData.positions = positions;
  34016. vertexData.normals = normals;
  34017. vertexData.uvs = uvs;
  34018. return vertexData;
  34019. };
  34020. /**
  34021. * Creates the VertexData of the Ground designed from a heightmap.
  34022. */
  34023. VertexData.CreateGroundFromHeightMap = function (options) {
  34024. var indices = [];
  34025. var positions = [];
  34026. var normals = [];
  34027. var uvs = [];
  34028. var row, col;
  34029. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  34030. // Vertices
  34031. for (row = 0; row <= options.subdivisions; row++) {
  34032. for (col = 0; col <= options.subdivisions; col++) {
  34033. 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));
  34034. // Compute height
  34035. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  34036. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  34037. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  34038. var r = options.buffer[pos] / 255.0;
  34039. var g = options.buffer[pos + 1] / 255.0;
  34040. var b = options.buffer[pos + 2] / 255.0;
  34041. var gradient = r * filter.r + g * filter.g + b * filter.b;
  34042. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  34043. // Add vertex
  34044. positions.push(position.x, position.y, position.z);
  34045. normals.push(0, 0, 0);
  34046. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  34047. }
  34048. }
  34049. // Indices
  34050. for (row = 0; row < options.subdivisions; row++) {
  34051. for (col = 0; col < options.subdivisions; col++) {
  34052. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34053. indices.push(col + 1 + row * (options.subdivisions + 1));
  34054. indices.push(col + row * (options.subdivisions + 1));
  34055. indices.push(col + (row + 1) * (options.subdivisions + 1));
  34056. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34057. indices.push(col + row * (options.subdivisions + 1));
  34058. }
  34059. }
  34060. // Normals
  34061. VertexData.ComputeNormals(positions, indices, normals);
  34062. // Result
  34063. var vertexData = new VertexData();
  34064. vertexData.indices = indices;
  34065. vertexData.positions = positions;
  34066. vertexData.normals = normals;
  34067. vertexData.uvs = uvs;
  34068. return vertexData;
  34069. };
  34070. /**
  34071. * Creates the VertexData of the Plane.
  34072. */
  34073. VertexData.CreatePlane = function (options) {
  34074. var indices = [];
  34075. var positions = [];
  34076. var normals = [];
  34077. var uvs = [];
  34078. var width = options.width || options.size || 1;
  34079. var height = options.height || options.size || 1;
  34080. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34081. // Vertices
  34082. var halfWidth = width / 2.0;
  34083. var halfHeight = height / 2.0;
  34084. positions.push(-halfWidth, -halfHeight, 0);
  34085. normals.push(0, 0, -1.0);
  34086. uvs.push(0.0, 0.0);
  34087. positions.push(halfWidth, -halfHeight, 0);
  34088. normals.push(0, 0, -1.0);
  34089. uvs.push(1.0, 0.0);
  34090. positions.push(halfWidth, halfHeight, 0);
  34091. normals.push(0, 0, -1.0);
  34092. uvs.push(1.0, 1.0);
  34093. positions.push(-halfWidth, halfHeight, 0);
  34094. normals.push(0, 0, -1.0);
  34095. uvs.push(0.0, 1.0);
  34096. // Indices
  34097. indices.push(0);
  34098. indices.push(1);
  34099. indices.push(2);
  34100. indices.push(0);
  34101. indices.push(2);
  34102. indices.push(3);
  34103. // Sides
  34104. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34105. // Result
  34106. var vertexData = new VertexData();
  34107. vertexData.indices = indices;
  34108. vertexData.positions = positions;
  34109. vertexData.normals = normals;
  34110. vertexData.uvs = uvs;
  34111. return vertexData;
  34112. };
  34113. /**
  34114. * Creates the VertexData of the Disc or regular Polygon.
  34115. */
  34116. VertexData.CreateDisc = function (options) {
  34117. var positions = new Array();
  34118. var indices = new Array();
  34119. var normals = new Array();
  34120. var uvs = new Array();
  34121. var radius = options.radius || 0.5;
  34122. var tessellation = options.tessellation || 64;
  34123. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  34124. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34125. // positions and uvs
  34126. positions.push(0, 0, 0); // disc center first
  34127. uvs.push(0.5, 0.5);
  34128. var theta = Math.PI * 2 * arc;
  34129. var step = theta / tessellation;
  34130. for (var a = 0; a < theta; a += step) {
  34131. var x = Math.cos(a);
  34132. var y = Math.sin(a);
  34133. var u = (x + 1) / 2;
  34134. var v = (1 - y) / 2;
  34135. positions.push(radius * x, radius * y, 0);
  34136. uvs.push(u, v);
  34137. }
  34138. if (arc === 1) {
  34139. positions.push(positions[3], positions[4], positions[5]); // close the circle
  34140. uvs.push(uvs[2], uvs[3]);
  34141. }
  34142. //indices
  34143. var vertexNb = positions.length / 3;
  34144. for (var i = 1; i < vertexNb - 1; i++) {
  34145. indices.push(i + 1, 0, i);
  34146. }
  34147. // result
  34148. VertexData.ComputeNormals(positions, indices, normals);
  34149. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34150. var vertexData = new VertexData();
  34151. vertexData.indices = indices;
  34152. vertexData.positions = positions;
  34153. vertexData.normals = normals;
  34154. vertexData.uvs = uvs;
  34155. return vertexData;
  34156. };
  34157. /**
  34158. * Re-creates the VertexData of the Polygon for sideOrientation.
  34159. */
  34160. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  34161. var faceUV = fUV || new Array(3);
  34162. var faceColors = fColors;
  34163. var colors = [];
  34164. // default face colors and UV if undefined
  34165. for (var f = 0; f < 3; f++) {
  34166. if (faceUV[f] === undefined) {
  34167. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34168. }
  34169. if (faceColors && faceColors[f] === undefined) {
  34170. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34171. }
  34172. }
  34173. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34174. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34175. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34176. var indices = polygon.getIndices();
  34177. // set face colours and textures
  34178. var idx = 0;
  34179. var face = 0;
  34180. for (var index = 0; index < normals.length; index += 3) {
  34181. //Edge Face no. 1
  34182. if (Math.abs(normals[index + 1]) < 0.001) {
  34183. face = 1;
  34184. }
  34185. //Top Face no. 0
  34186. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  34187. face = 0;
  34188. }
  34189. //Bottom Face no. 2
  34190. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  34191. face = 2;
  34192. }
  34193. idx = index / 3;
  34194. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  34195. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  34196. if (faceColors) {
  34197. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  34198. }
  34199. }
  34200. // sides
  34201. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  34202. // Result
  34203. var vertexData = new VertexData();
  34204. vertexData.indices = indices;
  34205. vertexData.positions = positions;
  34206. vertexData.normals = normals;
  34207. vertexData.uvs = uvs;
  34208. if (faceColors) {
  34209. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  34210. vertexData.colors = totalColors;
  34211. }
  34212. return vertexData;
  34213. };
  34214. /**
  34215. * Creates the VertexData of the IcoSphere.
  34216. */
  34217. VertexData.CreateIcoSphere = function (options) {
  34218. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34219. var radius = options.radius || 1;
  34220. var flat = (options.flat === undefined) ? true : options.flat;
  34221. var subdivisions = options.subdivisions || 4;
  34222. var radiusX = options.radiusX || radius;
  34223. var radiusY = options.radiusY || radius;
  34224. var radiusZ = options.radiusZ || radius;
  34225. var t = (1 + Math.sqrt(5)) / 2;
  34226. // 12 vertex x,y,z
  34227. var ico_vertices = [
  34228. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  34229. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  34230. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  34231. ];
  34232. // index of 3 vertex makes a face of icopshere
  34233. var ico_indices = [
  34234. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  34235. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  34236. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  34237. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  34238. ];
  34239. // vertex for uv have aliased position, not for UV
  34240. var vertices_unalias_id = [
  34241. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  34242. // vertex alias
  34243. 0,
  34244. 2,
  34245. 3,
  34246. 3,
  34247. 3,
  34248. 4,
  34249. 7,
  34250. 8,
  34251. 9,
  34252. 9,
  34253. 10,
  34254. 11 // 23: B + 12
  34255. ];
  34256. // uv as integer step (not pixels !)
  34257. var ico_vertexuv = [
  34258. 5, 1, 3, 1, 6, 4, 0, 0,
  34259. 5, 3, 4, 2, 2, 2, 4, 0,
  34260. 2, 0, 1, 1, 6, 0, 6, 2,
  34261. // vertex alias (for same vertex on different faces)
  34262. 0, 4,
  34263. 3, 3,
  34264. 4, 4,
  34265. 3, 1,
  34266. 4, 2,
  34267. 4, 4,
  34268. 0, 2,
  34269. 1, 1,
  34270. 2, 2,
  34271. 3, 3,
  34272. 1, 3,
  34273. 2, 4 // 23: B + 12
  34274. ];
  34275. // Vertices[0, 1, ...9, A, B] : position on UV plane
  34276. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  34277. // First island of uv mapping
  34278. // v = 4h 3+ 2
  34279. // v = 3h 9+ 4
  34280. // v = 2h 9+ 5 B
  34281. // v = 1h 9 1 0
  34282. // v = 0h 3 8 7 A
  34283. // u = 0 1 2 3 4 5 6 *a
  34284. // Second island of uv mapping
  34285. // v = 4h 0+ B+ 4+
  34286. // v = 3h A+ 2+
  34287. // v = 2h 7+ 6 3+
  34288. // v = 1h 8+ 3+
  34289. // v = 0h
  34290. // u = 0 1 2 3 4 5 6 *a
  34291. // Face layout on texture UV mapping
  34292. // ============
  34293. // \ 4 /\ 16 / ======
  34294. // \ / \ / /\ 11 /
  34295. // \/ 7 \/ / \ /
  34296. // ======= / 10 \/
  34297. // /\ 17 /\ =======
  34298. // / \ / \ \ 15 /\
  34299. // / 8 \/ 12 \ \ / \
  34300. // ============ \/ 6 \
  34301. // \ 18 /\ ============
  34302. // \ / \ \ 5 /\ 0 /
  34303. // \/ 13 \ \ / \ /
  34304. // ======= \/ 1 \/
  34305. // =============
  34306. // /\ 19 /\ 2 /\
  34307. // / \ / \ / \
  34308. // / 14 \/ 9 \/ 3 \
  34309. // ===================
  34310. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  34311. var ustep = 138 / 1024;
  34312. var vstep = 239 / 1024;
  34313. var uoffset = 60 / 1024;
  34314. var voffset = 26 / 1024;
  34315. // Second island should have margin, not to touch the first island
  34316. // avoid any borderline artefact in pixel rounding
  34317. var island_u_offset = -40 / 1024;
  34318. var island_v_offset = +20 / 1024;
  34319. // face is either island 0 or 1 :
  34320. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  34321. var island = [
  34322. 0, 0, 0, 0, 1,
  34323. 0, 0, 1, 1, 0,
  34324. 0, 0, 1, 1, 0,
  34325. 0, 1, 1, 1, 0 // 15 - 19
  34326. ];
  34327. var indices = new Array();
  34328. var positions = new Array();
  34329. var normals = new Array();
  34330. var uvs = new Array();
  34331. var current_indice = 0;
  34332. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  34333. var face_vertex_pos = new Array(3);
  34334. var face_vertex_uv = new Array(3);
  34335. var v012;
  34336. for (v012 = 0; v012 < 3; v012++) {
  34337. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  34338. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  34339. }
  34340. // create all with normals
  34341. for (var face = 0; face < 20; face++) {
  34342. // 3 vertex per face
  34343. for (v012 = 0; v012 < 3; v012++) {
  34344. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  34345. var v_id = ico_indices[3 * face + v012];
  34346. // vertex have 3D position (x,y,z)
  34347. 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]);
  34348. // Normalize to get normal, then scale to radius
  34349. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  34350. // uv Coordinates from vertex ID
  34351. 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);
  34352. }
  34353. // Subdivide the face (interpolate pos, norm, uv)
  34354. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  34355. // - norm is linear interpolation of vertex corner normal
  34356. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  34357. // - uv is linear interpolation
  34358. //
  34359. // Topology is as below for sub-divide by 2
  34360. // vertex shown as v0,v1,v2
  34361. // interp index is i1 to progress in range [v0,v1[
  34362. // interp index is i2 to progress in range [v0,v2[
  34363. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  34364. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34365. //
  34366. //
  34367. // i2 v2
  34368. // ^ ^
  34369. // / / \
  34370. // / / \
  34371. // / / \
  34372. // / / (0,1) \
  34373. // / #---------\
  34374. // / / \ (0,0)'/ \
  34375. // / / \ / \
  34376. // / / \ / \
  34377. // / / (0,0) \ / (1,0) \
  34378. // / #---------#---------\
  34379. // v0 v1
  34380. //
  34381. // --------------------> i1
  34382. //
  34383. // interp of (i1,i2):
  34384. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  34385. // along i1 : lerp(x0,x1, i1/(S-i2))
  34386. //
  34387. // centroid of triangle is needed to get help normal computation
  34388. // (c1,c2) are used for centroid location
  34389. var interp_vertex = function (i1, i2, c1, c2) {
  34390. // vertex is interpolated from
  34391. // - face_vertex_pos[0..2]
  34392. // - face_vertex_uv[0..2]
  34393. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  34394. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  34395. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  34396. pos_interp.normalize();
  34397. var vertex_normal;
  34398. if (flat) {
  34399. // in flat mode, recalculate normal as face centroid normal
  34400. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  34401. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  34402. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  34403. }
  34404. else {
  34405. // in smooth mode, recalculate normal from each single vertex position
  34406. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  34407. }
  34408. // Vertex normal need correction due to X,Y,Z radius scaling
  34409. vertex_normal.x /= radiusX;
  34410. vertex_normal.y /= radiusY;
  34411. vertex_normal.z /= radiusZ;
  34412. vertex_normal.normalize();
  34413. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  34414. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  34415. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  34416. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  34417. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  34418. uvs.push(uv_interp.x, uv_interp.y);
  34419. // push each vertex has member of a face
  34420. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  34421. indices.push(current_indice);
  34422. current_indice++;
  34423. };
  34424. for (var i2 = 0; i2 < subdivisions; i2++) {
  34425. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  34426. // face : (i1,i2) for /\ :
  34427. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  34428. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34429. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34430. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34431. if (i1 + i2 + 1 < subdivisions) {
  34432. // face : (i1,i2)' for \/ :
  34433. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34434. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34435. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34436. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34437. }
  34438. }
  34439. }
  34440. }
  34441. // Sides
  34442. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34443. // Result
  34444. var vertexData = new VertexData();
  34445. vertexData.indices = indices;
  34446. vertexData.positions = positions;
  34447. vertexData.normals = normals;
  34448. vertexData.uvs = uvs;
  34449. return vertexData;
  34450. };
  34451. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34452. /**
  34453. * Creates the VertexData of the Polyhedron.
  34454. */
  34455. VertexData.CreatePolyhedron = function (options) {
  34456. // provided polyhedron types :
  34457. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34458. // 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)
  34459. var polyhedra = [];
  34460. 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]] };
  34461. 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]] };
  34462. polyhedra[2] = {
  34463. 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]],
  34464. 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]]
  34465. };
  34466. polyhedra[3] = {
  34467. 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]],
  34468. 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]]
  34469. };
  34470. polyhedra[4] = {
  34471. 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]],
  34472. 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]]
  34473. };
  34474. 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]] };
  34475. 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]] };
  34476. 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]] };
  34477. 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]] };
  34478. 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]] };
  34479. 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]] };
  34480. 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]] };
  34481. 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]] };
  34482. 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]] };
  34483. polyhedra[14] = {
  34484. 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]],
  34485. 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]]
  34486. };
  34487. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34488. var size = options.size;
  34489. var sizeX = options.sizeX || size || 1;
  34490. var sizeY = options.sizeY || size || 1;
  34491. var sizeZ = options.sizeZ || size || 1;
  34492. var data = options.custom || polyhedra[type];
  34493. var nbfaces = data.face.length;
  34494. var faceUV = options.faceUV || new Array(nbfaces);
  34495. var faceColors = options.faceColors;
  34496. var flat = (options.flat === undefined) ? true : options.flat;
  34497. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34498. var positions = new Array();
  34499. var indices = new Array();
  34500. var normals = new Array();
  34501. var uvs = new Array();
  34502. var colors = new Array();
  34503. var index = 0;
  34504. var faceIdx = 0; // face cursor in the array "indexes"
  34505. var indexes = new Array();
  34506. var i = 0;
  34507. var f = 0;
  34508. var u, v, ang, x, y, tmp;
  34509. // default face colors and UV if undefined
  34510. if (flat) {
  34511. for (f = 0; f < nbfaces; f++) {
  34512. if (faceColors && faceColors[f] === undefined) {
  34513. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34514. }
  34515. if (faceUV && faceUV[f] === undefined) {
  34516. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34517. }
  34518. }
  34519. }
  34520. if (!flat) {
  34521. for (i = 0; i < data.vertex.length; i++) {
  34522. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34523. uvs.push(0, 0);
  34524. }
  34525. for (f = 0; f < nbfaces; f++) {
  34526. for (i = 0; i < data.face[f].length - 2; i++) {
  34527. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34528. }
  34529. }
  34530. }
  34531. else {
  34532. for (f = 0; f < nbfaces; f++) {
  34533. var fl = data.face[f].length; // number of vertices of the current face
  34534. ang = 2 * Math.PI / fl;
  34535. x = 0.5 * Math.tan(ang / 2);
  34536. y = 0.5;
  34537. // positions, uvs, colors
  34538. for (i = 0; i < fl; i++) {
  34539. // positions
  34540. 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);
  34541. indexes.push(index);
  34542. index++;
  34543. // uvs
  34544. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34545. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34546. uvs.push(u, v);
  34547. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34548. y = x * Math.sin(ang) + y * Math.cos(ang);
  34549. x = tmp;
  34550. // colors
  34551. if (faceColors) {
  34552. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34553. }
  34554. }
  34555. // indices from indexes
  34556. for (i = 0; i < fl - 2; i++) {
  34557. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34558. }
  34559. faceIdx += fl;
  34560. }
  34561. }
  34562. VertexData.ComputeNormals(positions, indices, normals);
  34563. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34564. var vertexData = new VertexData();
  34565. vertexData.positions = positions;
  34566. vertexData.indices = indices;
  34567. vertexData.normals = normals;
  34568. vertexData.uvs = uvs;
  34569. if (faceColors && flat) {
  34570. vertexData.colors = colors;
  34571. }
  34572. return vertexData;
  34573. };
  34574. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34575. /**
  34576. * Creates the VertexData of the Torus Knot.
  34577. */
  34578. VertexData.CreateTorusKnot = function (options) {
  34579. var indices = new Array();
  34580. var positions = new Array();
  34581. var normals = new Array();
  34582. var uvs = new Array();
  34583. var radius = options.radius || 2;
  34584. var tube = options.tube || 0.5;
  34585. var radialSegments = options.radialSegments || 32;
  34586. var tubularSegments = options.tubularSegments || 32;
  34587. var p = options.p || 2;
  34588. var q = options.q || 3;
  34589. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34590. // Helper
  34591. var getPos = function (angle) {
  34592. var cu = Math.cos(angle);
  34593. var su = Math.sin(angle);
  34594. var quOverP = q / p * angle;
  34595. var cs = Math.cos(quOverP);
  34596. var tx = radius * (2 + cs) * 0.5 * cu;
  34597. var ty = radius * (2 + cs) * su * 0.5;
  34598. var tz = radius * Math.sin(quOverP) * 0.5;
  34599. return new BABYLON.Vector3(tx, ty, tz);
  34600. };
  34601. // Vertices
  34602. var i;
  34603. var j;
  34604. for (i = 0; i <= radialSegments; i++) {
  34605. var modI = i % radialSegments;
  34606. var u = modI / radialSegments * 2 * p * Math.PI;
  34607. var p1 = getPos(u);
  34608. var p2 = getPos(u + 0.01);
  34609. var tang = p2.subtract(p1);
  34610. var n = p2.add(p1);
  34611. var bitan = BABYLON.Vector3.Cross(tang, n);
  34612. n = BABYLON.Vector3.Cross(bitan, tang);
  34613. bitan.normalize();
  34614. n.normalize();
  34615. for (j = 0; j < tubularSegments; j++) {
  34616. var modJ = j % tubularSegments;
  34617. var v = modJ / tubularSegments * 2 * Math.PI;
  34618. var cx = -tube * Math.cos(v);
  34619. var cy = tube * Math.sin(v);
  34620. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34621. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34622. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34623. uvs.push(i / radialSegments);
  34624. uvs.push(j / tubularSegments);
  34625. }
  34626. }
  34627. for (i = 0; i < radialSegments; i++) {
  34628. for (j = 0; j < tubularSegments; j++) {
  34629. var jNext = (j + 1) % tubularSegments;
  34630. var a = i * tubularSegments + j;
  34631. var b = (i + 1) * tubularSegments + j;
  34632. var c = (i + 1) * tubularSegments + jNext;
  34633. var d = i * tubularSegments + jNext;
  34634. indices.push(d);
  34635. indices.push(b);
  34636. indices.push(a);
  34637. indices.push(d);
  34638. indices.push(c);
  34639. indices.push(b);
  34640. }
  34641. }
  34642. // Normals
  34643. VertexData.ComputeNormals(positions, indices, normals);
  34644. // Sides
  34645. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34646. // Result
  34647. var vertexData = new VertexData();
  34648. vertexData.indices = indices;
  34649. vertexData.positions = positions;
  34650. vertexData.normals = normals;
  34651. vertexData.uvs = uvs;
  34652. return vertexData;
  34653. };
  34654. // Tools
  34655. /**
  34656. * @param {any} - positions (number[] or Float32Array)
  34657. * @param {any} - indices (number[] or Uint16Array)
  34658. * @param {any} - normals (number[] or Float32Array)
  34659. * options (optional) :
  34660. * facetPositions : optional array of facet positions (vector3)
  34661. * facetNormals : optional array of facet normals (vector3)
  34662. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34663. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34664. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34665. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34666. * bInfo : optional bounding info, required for facetPartitioning computation
  34667. * useRightHandedSystem: optional boolean to for right handed system computation
  34668. * depthSort : optional boolean to enable the facet depth sort computation
  34669. * distanceTo : optional Vector3 to compute the facet depth from this location
  34670. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34671. */
  34672. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34673. // temporary scalar variables
  34674. var index = 0; // facet index
  34675. var p1p2x = 0.0; // p1p2 vector x coordinate
  34676. var p1p2y = 0.0; // p1p2 vector y coordinate
  34677. var p1p2z = 0.0; // p1p2 vector z coordinate
  34678. var p3p2x = 0.0; // p3p2 vector x coordinate
  34679. var p3p2y = 0.0; // p3p2 vector y coordinate
  34680. var p3p2z = 0.0; // p3p2 vector z coordinate
  34681. var faceNormalx = 0.0; // facet normal x coordinate
  34682. var faceNormaly = 0.0; // facet normal y coordinate
  34683. var faceNormalz = 0.0; // facet normal z coordinate
  34684. var length = 0.0; // facet normal length before normalization
  34685. var v1x = 0; // vector1 x index in the positions array
  34686. var v1y = 0; // vector1 y index in the positions array
  34687. var v1z = 0; // vector1 z index in the positions array
  34688. var v2x = 0; // vector2 x index in the positions array
  34689. var v2y = 0; // vector2 y index in the positions array
  34690. var v2z = 0; // vector2 z index in the positions array
  34691. var v3x = 0; // vector3 x index in the positions array
  34692. var v3y = 0; // vector3 y index in the positions array
  34693. var v3z = 0; // vector3 z index in the positions array
  34694. var computeFacetNormals = false;
  34695. var computeFacetPositions = false;
  34696. var computeFacetPartitioning = false;
  34697. var computeDepthSort = false;
  34698. var faceNormalSign = 1;
  34699. var ratio = 0;
  34700. var distanceTo = null;
  34701. if (options) {
  34702. computeFacetNormals = (options.facetNormals) ? true : false;
  34703. computeFacetPositions = (options.facetPositions) ? true : false;
  34704. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34705. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34706. ratio = options.ratio || 0;
  34707. computeDepthSort = (options.depthSort) ? true : false;
  34708. distanceTo = (options.distanceTo);
  34709. if (computeDepthSort) {
  34710. if (distanceTo === undefined) {
  34711. distanceTo = BABYLON.Vector3.Zero();
  34712. }
  34713. var depthSortedFacets = options.depthSortedFacets;
  34714. }
  34715. }
  34716. // facetPartitioning reinit if needed
  34717. var xSubRatio = 0;
  34718. var ySubRatio = 0;
  34719. var zSubRatio = 0;
  34720. var subSq = 0;
  34721. if (computeFacetPartitioning && options && options.bbSize) {
  34722. var ox = 0; // X partitioning index for facet position
  34723. var oy = 0; // Y partinioning index for facet position
  34724. var oz = 0; // Z partinioning index for facet position
  34725. var b1x = 0; // X partitioning index for facet v1 vertex
  34726. var b1y = 0; // Y partitioning index for facet v1 vertex
  34727. var b1z = 0; // z partitioning index for facet v1 vertex
  34728. var b2x = 0; // X partitioning index for facet v2 vertex
  34729. var b2y = 0; // Y partitioning index for facet v2 vertex
  34730. var b2z = 0; // Z partitioning index for facet v2 vertex
  34731. var b3x = 0; // X partitioning index for facet v3 vertex
  34732. var b3y = 0; // Y partitioning index for facet v3 vertex
  34733. var b3z = 0; // Z partitioning index for facet v3 vertex
  34734. var block_idx_o = 0; // facet barycenter block index
  34735. var block_idx_v1 = 0; // v1 vertex block index
  34736. var block_idx_v2 = 0; // v2 vertex block index
  34737. var block_idx_v3 = 0; // v3 vertex block index
  34738. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34739. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34740. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34741. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34742. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34743. subSq = options.subDiv.max * options.subDiv.max;
  34744. options.facetPartitioning.length = 0;
  34745. }
  34746. // reset the normals
  34747. for (index = 0; index < positions.length; index++) {
  34748. normals[index] = 0.0;
  34749. }
  34750. // Loop : 1 indice triplet = 1 facet
  34751. var nbFaces = (indices.length / 3) | 0;
  34752. for (index = 0; index < nbFaces; index++) {
  34753. // get the indexes of the coordinates of each vertex of the facet
  34754. v1x = indices[index * 3] * 3;
  34755. v1y = v1x + 1;
  34756. v1z = v1x + 2;
  34757. v2x = indices[index * 3 + 1] * 3;
  34758. v2y = v2x + 1;
  34759. v2z = v2x + 2;
  34760. v3x = indices[index * 3 + 2] * 3;
  34761. v3y = v3x + 1;
  34762. v3z = v3x + 2;
  34763. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34764. p1p2y = positions[v1y] - positions[v2y];
  34765. p1p2z = positions[v1z] - positions[v2z];
  34766. p3p2x = positions[v3x] - positions[v2x];
  34767. p3p2y = positions[v3y] - positions[v2y];
  34768. p3p2z = positions[v3z] - positions[v2z];
  34769. // compute the face normal with the cross product
  34770. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34771. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34772. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34773. // normalize this normal and store it in the array facetData
  34774. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34775. length = (length === 0) ? 1.0 : length;
  34776. faceNormalx /= length;
  34777. faceNormaly /= length;
  34778. faceNormalz /= length;
  34779. if (computeFacetNormals && options) {
  34780. options.facetNormals[index].x = faceNormalx;
  34781. options.facetNormals[index].y = faceNormaly;
  34782. options.facetNormals[index].z = faceNormalz;
  34783. }
  34784. if (computeFacetPositions && options) {
  34785. // compute and the facet barycenter coordinates in the array facetPositions
  34786. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34787. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34788. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34789. }
  34790. if (computeFacetPartitioning && options) {
  34791. // store the facet indexes in arrays in the main facetPartitioning array :
  34792. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34793. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  34794. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  34795. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  34796. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34797. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34798. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34799. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34800. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34801. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34802. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34803. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34804. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34805. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34806. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34807. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34808. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34809. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34810. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34811. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34812. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34813. // push each facet index in each block containing the vertex
  34814. options.facetPartitioning[block_idx_v1].push(index);
  34815. if (block_idx_v2 != block_idx_v1) {
  34816. options.facetPartitioning[block_idx_v2].push(index);
  34817. }
  34818. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34819. options.facetPartitioning[block_idx_v3].push(index);
  34820. }
  34821. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34822. options.facetPartitioning[block_idx_o].push(index);
  34823. }
  34824. }
  34825. if (computeDepthSort && options && options.facetPositions) {
  34826. var dsf = depthSortedFacets[index];
  34827. dsf.ind = index * 3;
  34828. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  34829. }
  34830. // compute the normals anyway
  34831. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34832. normals[v1y] += faceNormaly;
  34833. normals[v1z] += faceNormalz;
  34834. normals[v2x] += faceNormalx;
  34835. normals[v2y] += faceNormaly;
  34836. normals[v2z] += faceNormalz;
  34837. normals[v3x] += faceNormalx;
  34838. normals[v3y] += faceNormaly;
  34839. normals[v3z] += faceNormalz;
  34840. }
  34841. // last normalization of each normal
  34842. for (index = 0; index < normals.length / 3; index++) {
  34843. faceNormalx = normals[index * 3];
  34844. faceNormaly = normals[index * 3 + 1];
  34845. faceNormalz = normals[index * 3 + 2];
  34846. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34847. length = (length === 0) ? 1.0 : length;
  34848. faceNormalx /= length;
  34849. faceNormaly /= length;
  34850. faceNormalz /= length;
  34851. normals[index * 3] = faceNormalx;
  34852. normals[index * 3 + 1] = faceNormaly;
  34853. normals[index * 3 + 2] = faceNormalz;
  34854. }
  34855. };
  34856. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  34857. var li = indices.length;
  34858. var ln = normals.length;
  34859. var i;
  34860. var n;
  34861. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34862. switch (sideOrientation) {
  34863. case BABYLON.Mesh.FRONTSIDE:
  34864. // nothing changed
  34865. break;
  34866. case BABYLON.Mesh.BACKSIDE:
  34867. var tmp;
  34868. // indices
  34869. for (i = 0; i < li; i += 3) {
  34870. tmp = indices[i];
  34871. indices[i] = indices[i + 2];
  34872. indices[i + 2] = tmp;
  34873. }
  34874. // normals
  34875. for (n = 0; n < ln; n++) {
  34876. normals[n] = -normals[n];
  34877. }
  34878. break;
  34879. case BABYLON.Mesh.DOUBLESIDE:
  34880. // positions
  34881. var lp = positions.length;
  34882. var l = lp / 3;
  34883. for (var p = 0; p < lp; p++) {
  34884. positions[lp + p] = positions[p];
  34885. }
  34886. // indices
  34887. for (i = 0; i < li; i += 3) {
  34888. indices[i + li] = indices[i + 2] + l;
  34889. indices[i + 1 + li] = indices[i + 1] + l;
  34890. indices[i + 2 + li] = indices[i] + l;
  34891. }
  34892. // normals
  34893. for (n = 0; n < ln; n++) {
  34894. normals[ln + n] = -normals[n];
  34895. }
  34896. // uvs
  34897. var lu = uvs.length;
  34898. var u = 0;
  34899. for (u = 0; u < lu; u++) {
  34900. uvs[u + lu] = uvs[u];
  34901. }
  34902. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34903. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34904. u = 0;
  34905. for (i = 0; i < lu / 2; i++) {
  34906. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  34907. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  34908. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  34909. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  34910. u += 2;
  34911. }
  34912. break;
  34913. }
  34914. };
  34915. /**
  34916. * Creates a new VertexData from the imported parameters.
  34917. */
  34918. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  34919. var vertexData = new VertexData();
  34920. // positions
  34921. var positions = parsedVertexData.positions;
  34922. if (positions) {
  34923. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  34924. }
  34925. // normals
  34926. var normals = parsedVertexData.normals;
  34927. if (normals) {
  34928. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  34929. }
  34930. // tangents
  34931. var tangents = parsedVertexData.tangents;
  34932. if (tangents) {
  34933. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  34934. }
  34935. // uvs
  34936. var uvs = parsedVertexData.uvs;
  34937. if (uvs) {
  34938. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  34939. }
  34940. // uv2s
  34941. var uv2s = parsedVertexData.uv2s;
  34942. if (uv2s) {
  34943. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  34944. }
  34945. // uv3s
  34946. var uv3s = parsedVertexData.uv3s;
  34947. if (uv3s) {
  34948. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  34949. }
  34950. // uv4s
  34951. var uv4s = parsedVertexData.uv4s;
  34952. if (uv4s) {
  34953. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  34954. }
  34955. // uv5s
  34956. var uv5s = parsedVertexData.uv5s;
  34957. if (uv5s) {
  34958. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  34959. }
  34960. // uv6s
  34961. var uv6s = parsedVertexData.uv6s;
  34962. if (uv6s) {
  34963. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  34964. }
  34965. // colors
  34966. var colors = parsedVertexData.colors;
  34967. if (colors) {
  34968. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  34969. }
  34970. // matricesIndices
  34971. var matricesIndices = parsedVertexData.matricesIndices;
  34972. if (matricesIndices) {
  34973. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  34974. }
  34975. // matricesWeights
  34976. var matricesWeights = parsedVertexData.matricesWeights;
  34977. if (matricesWeights) {
  34978. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  34979. }
  34980. // indices
  34981. var indices = parsedVertexData.indices;
  34982. if (indices) {
  34983. vertexData.indices = indices;
  34984. }
  34985. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  34986. };
  34987. return VertexData;
  34988. }());
  34989. BABYLON.VertexData = VertexData;
  34990. })(BABYLON || (BABYLON = {}));
  34991. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  34992. var BABYLON;
  34993. (function (BABYLON) {
  34994. /**
  34995. * Class used to store geometry data (vertex buffers + index buffer)
  34996. */
  34997. var Geometry = /** @class */ (function () {
  34998. /**
  34999. * Creates a new geometry
  35000. * @param id defines the unique ID
  35001. * @param scene defines the hosting scene
  35002. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  35003. * @param updatable defines if geometry must be updatable (false by default)
  35004. * @param mesh defines the mesh that will be associated with the geometry
  35005. */
  35006. function Geometry(id, scene, vertexData, updatable, mesh) {
  35007. if (updatable === void 0) { updatable = false; }
  35008. if (mesh === void 0) { mesh = null; }
  35009. /**
  35010. * Gets the delay loading state of the geometry (none by default which means not delayed)
  35011. */
  35012. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35013. this._totalVertices = 0;
  35014. this._isDisposed = false;
  35015. this._indexBufferIsUpdatable = false;
  35016. this.id = id;
  35017. this._engine = scene.getEngine();
  35018. this._meshes = [];
  35019. this._scene = scene;
  35020. //Init vertex buffer cache
  35021. this._vertexBuffers = {};
  35022. this._indices = [];
  35023. this._updatable = updatable;
  35024. // vertexData
  35025. if (vertexData) {
  35026. this.setAllVerticesData(vertexData, updatable);
  35027. }
  35028. else {
  35029. this._totalVertices = 0;
  35030. this._indices = [];
  35031. }
  35032. if (this._engine.getCaps().vertexArrayObject) {
  35033. this._vertexArrayObjects = {};
  35034. }
  35035. // applyToMesh
  35036. if (mesh) {
  35037. if (mesh.getClassName() === "LinesMesh") {
  35038. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  35039. this.updateExtend();
  35040. }
  35041. this.applyToMesh(mesh);
  35042. mesh.computeWorldMatrix(true);
  35043. }
  35044. }
  35045. Object.defineProperty(Geometry.prototype, "boundingBias", {
  35046. /**
  35047. * 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
  35048. */
  35049. get: function () {
  35050. return this._boundingBias;
  35051. },
  35052. /**
  35053. * 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
  35054. */
  35055. set: function (value) {
  35056. if (this._boundingBias && this._boundingBias.equals(value)) {
  35057. return;
  35058. }
  35059. this._boundingBias = value.clone();
  35060. this.updateBoundingInfo(true, null);
  35061. },
  35062. enumerable: true,
  35063. configurable: true
  35064. });
  35065. /**
  35066. * Static function used to attach a new empty geometry to a mesh
  35067. * @param mesh defines the mesh to attach the geometry to
  35068. * @returns the new {BABYLON.Geometry}
  35069. */
  35070. Geometry.CreateGeometryForMesh = function (mesh) {
  35071. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  35072. geometry.applyToMesh(mesh);
  35073. return geometry;
  35074. };
  35075. Object.defineProperty(Geometry.prototype, "extend", {
  35076. /**
  35077. * Gets the current extend of the geometry
  35078. */
  35079. get: function () {
  35080. return this._extend;
  35081. },
  35082. enumerable: true,
  35083. configurable: true
  35084. });
  35085. /**
  35086. * Gets the hosting scene
  35087. * @returns the hosting {BABYLON.Scene}
  35088. */
  35089. Geometry.prototype.getScene = function () {
  35090. return this._scene;
  35091. };
  35092. /**
  35093. * Gets the hosting engine
  35094. * @returns the hosting {BABYLON.Engine}
  35095. */
  35096. Geometry.prototype.getEngine = function () {
  35097. return this._engine;
  35098. };
  35099. /**
  35100. * Defines if the geometry is ready to use
  35101. * @returns true if the geometry is ready to be used
  35102. */
  35103. Geometry.prototype.isReady = function () {
  35104. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  35105. };
  35106. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  35107. /**
  35108. * Gets a value indicating that the geometry should not be serialized
  35109. */
  35110. get: function () {
  35111. for (var index = 0; index < this._meshes.length; index++) {
  35112. if (!this._meshes[index].doNotSerialize) {
  35113. return false;
  35114. }
  35115. }
  35116. return true;
  35117. },
  35118. enumerable: true,
  35119. configurable: true
  35120. });
  35121. /** @ignore */
  35122. Geometry.prototype._rebuild = function () {
  35123. if (this._vertexArrayObjects) {
  35124. this._vertexArrayObjects = {};
  35125. }
  35126. // Index buffer
  35127. if (this._meshes.length !== 0 && this._indices) {
  35128. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35129. }
  35130. // Vertex buffers
  35131. for (var key in this._vertexBuffers) {
  35132. var vertexBuffer = this._vertexBuffers[key];
  35133. vertexBuffer._rebuild();
  35134. }
  35135. };
  35136. /**
  35137. * Affects all gemetry data in one call
  35138. * @param vertexData defines the geometry data
  35139. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  35140. */
  35141. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35142. vertexData.applyToGeometry(this, updatable);
  35143. this.notifyUpdate();
  35144. };
  35145. /**
  35146. * Set specific vertex data
  35147. * @param kind defines the data kind (Position, normal, etc...)
  35148. * @param data defines the vertex data to use
  35149. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  35150. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  35151. */
  35152. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  35153. if (updatable === void 0) { updatable = false; }
  35154. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  35155. this.setVerticesBuffer(buffer);
  35156. };
  35157. /**
  35158. * Removes a specific vertex data
  35159. * @param kind defines the data kind (Position, normal, etc...)
  35160. */
  35161. Geometry.prototype.removeVerticesData = function (kind) {
  35162. if (this._vertexBuffers[kind]) {
  35163. this._vertexBuffers[kind].dispose();
  35164. delete this._vertexBuffers[kind];
  35165. }
  35166. };
  35167. /**
  35168. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  35169. * @param buffer defines the vertex buffer to use
  35170. */
  35171. Geometry.prototype.setVerticesBuffer = function (buffer) {
  35172. var kind = buffer.getKind();
  35173. if (this._vertexBuffers[kind]) {
  35174. this._vertexBuffers[kind].dispose();
  35175. }
  35176. this._vertexBuffers[kind] = buffer;
  35177. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35178. var data = buffer.getData();
  35179. var stride = buffer.getStrideSize();
  35180. this._totalVertices = data.length / stride;
  35181. this.updateExtend(data, stride);
  35182. this._resetPointsArrayCache();
  35183. var meshes = this._meshes;
  35184. var numOfMeshes = meshes.length;
  35185. for (var index = 0; index < numOfMeshes; index++) {
  35186. var mesh = meshes[index];
  35187. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35188. mesh._createGlobalSubMesh(false);
  35189. mesh.computeWorldMatrix(true);
  35190. }
  35191. }
  35192. this.notifyUpdate(kind);
  35193. if (this._vertexArrayObjects) {
  35194. this._disposeVertexArrayObjects();
  35195. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  35196. }
  35197. };
  35198. /**
  35199. * Update a specific vertex buffer
  35200. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  35201. * It will do nothing if the buffer is not updatable
  35202. * @param kind defines the data kind (Position, normal, etc...)
  35203. * @param data defines the data to use
  35204. * @param offset defines the offset in the target buffer where to store the data
  35205. */
  35206. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  35207. var vertexBuffer = this.getVertexBuffer(kind);
  35208. if (!vertexBuffer) {
  35209. return;
  35210. }
  35211. vertexBuffer.updateDirectly(data, offset);
  35212. this.notifyUpdate(kind);
  35213. };
  35214. /**
  35215. * Update a specific vertex buffer
  35216. * This function will create a new buffer if the current one is not updatable
  35217. * @param kind defines the data kind (Position, normal, etc...)
  35218. * @param data defines the data to use
  35219. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  35220. */
  35221. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  35222. if (updateExtends === void 0) { updateExtends = false; }
  35223. var vertexBuffer = this.getVertexBuffer(kind);
  35224. if (!vertexBuffer) {
  35225. return;
  35226. }
  35227. vertexBuffer.update(data);
  35228. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35229. var stride = vertexBuffer.getStrideSize();
  35230. this._totalVertices = data.length / stride;
  35231. this.updateBoundingInfo(updateExtends, data);
  35232. }
  35233. this.notifyUpdate(kind);
  35234. };
  35235. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  35236. if (updateExtends) {
  35237. this.updateExtend(data);
  35238. }
  35239. var meshes = this._meshes;
  35240. var numOfMeshes = meshes.length;
  35241. this._resetPointsArrayCache();
  35242. for (var index = 0; index < numOfMeshes; index++) {
  35243. var mesh = meshes[index];
  35244. if (updateExtends) {
  35245. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35246. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  35247. var subMesh = mesh.subMeshes[subIndex];
  35248. subMesh.refreshBoundingInfo();
  35249. }
  35250. }
  35251. }
  35252. };
  35253. /** @ignore */
  35254. Geometry.prototype._bind = function (effect, indexToBind) {
  35255. if (!effect) {
  35256. return;
  35257. }
  35258. if (indexToBind === undefined) {
  35259. indexToBind = this._indexBuffer;
  35260. }
  35261. var vbs = this.getVertexBuffers();
  35262. if (!vbs) {
  35263. return;
  35264. }
  35265. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  35266. this._engine.bindBuffers(vbs, indexToBind, effect);
  35267. return;
  35268. }
  35269. // Using VAO
  35270. if (!this._vertexArrayObjects[effect.key]) {
  35271. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  35272. }
  35273. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  35274. };
  35275. /**
  35276. * Gets total number of vertices
  35277. * @returns the total number of vertices
  35278. */
  35279. Geometry.prototype.getTotalVertices = function () {
  35280. if (!this.isReady()) {
  35281. return 0;
  35282. }
  35283. return this._totalVertices;
  35284. };
  35285. /**
  35286. * Gets a specific vertex data attached to this geometry
  35287. * @param kind defines the data kind (Position, normal, etc...)
  35288. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35289. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  35290. * @returns a float array containing vertex data
  35291. */
  35292. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  35293. var vertexBuffer = this.getVertexBuffer(kind);
  35294. if (!vertexBuffer) {
  35295. return null;
  35296. }
  35297. var orig = vertexBuffer.getData();
  35298. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  35299. return orig;
  35300. }
  35301. else {
  35302. var len = orig.length;
  35303. var copy = [];
  35304. for (var i = 0; i < len; i++) {
  35305. copy.push(orig[i]);
  35306. }
  35307. return copy;
  35308. }
  35309. };
  35310. /**
  35311. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  35312. * @param kind defines the data kind (Position, normal, etc...)
  35313. * @returns true if the vertex buffer with the specified kind is updatable
  35314. */
  35315. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  35316. var vb = this._vertexBuffers[kind];
  35317. if (!vb) {
  35318. return false;
  35319. }
  35320. return vb.isUpdatable();
  35321. };
  35322. /**
  35323. * Gets a specific vertex buffer
  35324. * @param kind defines the data kind (Position, normal, etc...)
  35325. * @returns a {BABYLON.VertexBuffer}
  35326. */
  35327. Geometry.prototype.getVertexBuffer = function (kind) {
  35328. if (!this.isReady()) {
  35329. return null;
  35330. }
  35331. return this._vertexBuffers[kind];
  35332. };
  35333. /**
  35334. * Returns all vertex buffers
  35335. * @return an object holding all vertex buffers indexed by kind
  35336. */
  35337. Geometry.prototype.getVertexBuffers = function () {
  35338. if (!this.isReady()) {
  35339. return null;
  35340. }
  35341. return this._vertexBuffers;
  35342. };
  35343. /**
  35344. * Gets a boolean indicating if specific vertex buffer is present
  35345. * @param kind defines the data kind (Position, normal, etc...)
  35346. * @returns true if data is present
  35347. */
  35348. Geometry.prototype.isVerticesDataPresent = function (kind) {
  35349. if (!this._vertexBuffers) {
  35350. if (this._delayInfo) {
  35351. return this._delayInfo.indexOf(kind) !== -1;
  35352. }
  35353. return false;
  35354. }
  35355. return this._vertexBuffers[kind] !== undefined;
  35356. };
  35357. /**
  35358. * Gets a list of all attached data kinds (Position, normal, etc...)
  35359. * @returns a list of string containing all kinds
  35360. */
  35361. Geometry.prototype.getVerticesDataKinds = function () {
  35362. var result = [];
  35363. var kind;
  35364. if (!this._vertexBuffers && this._delayInfo) {
  35365. for (kind in this._delayInfo) {
  35366. result.push(kind);
  35367. }
  35368. }
  35369. else {
  35370. for (kind in this._vertexBuffers) {
  35371. result.push(kind);
  35372. }
  35373. }
  35374. return result;
  35375. };
  35376. /**
  35377. * Update index buffer
  35378. * @param indices defines the indices to store in the index buffer
  35379. * @param offset defines the offset in the target buffer where to store the data
  35380. */
  35381. Geometry.prototype.updateIndices = function (indices, offset) {
  35382. if (!this._indexBuffer) {
  35383. return;
  35384. }
  35385. if (!this._indexBufferIsUpdatable) {
  35386. this.setIndices(indices, null, true);
  35387. }
  35388. else {
  35389. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  35390. }
  35391. };
  35392. /**
  35393. * Creates a new index buffer
  35394. * @param indices defines the indices to store in the index buffer
  35395. * @param totalVertices defines the total number of vertices (could be null)
  35396. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  35397. */
  35398. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  35399. if (totalVertices === void 0) { totalVertices = null; }
  35400. if (updatable === void 0) { updatable = false; }
  35401. if (this._indexBuffer) {
  35402. this._engine._releaseBuffer(this._indexBuffer);
  35403. }
  35404. this._disposeVertexArrayObjects();
  35405. this._indices = indices;
  35406. this._indexBufferIsUpdatable = updatable;
  35407. if (this._meshes.length !== 0 && this._indices) {
  35408. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  35409. }
  35410. if (totalVertices != undefined) {
  35411. this._totalVertices = totalVertices;
  35412. }
  35413. var meshes = this._meshes;
  35414. var numOfMeshes = meshes.length;
  35415. for (var index = 0; index < numOfMeshes; index++) {
  35416. meshes[index]._createGlobalSubMesh(true);
  35417. }
  35418. this.notifyUpdate();
  35419. };
  35420. /**
  35421. * Return the total number of indices
  35422. * @returns the total number of indices
  35423. */
  35424. Geometry.prototype.getTotalIndices = function () {
  35425. if (!this.isReady()) {
  35426. return 0;
  35427. }
  35428. return this._indices.length;
  35429. };
  35430. /**
  35431. * Gets the index buffer array
  35432. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35433. * @returns the index buffer array
  35434. */
  35435. Geometry.prototype.getIndices = function (copyWhenShared) {
  35436. if (!this.isReady()) {
  35437. return null;
  35438. }
  35439. var orig = this._indices;
  35440. if (!copyWhenShared || this._meshes.length === 1) {
  35441. return orig;
  35442. }
  35443. else {
  35444. var len = orig.length;
  35445. var copy = [];
  35446. for (var i = 0; i < len; i++) {
  35447. copy.push(orig[i]);
  35448. }
  35449. return copy;
  35450. }
  35451. };
  35452. /**
  35453. * Gets the index buffer
  35454. * @return the index buffer
  35455. */
  35456. Geometry.prototype.getIndexBuffer = function () {
  35457. if (!this.isReady()) {
  35458. return null;
  35459. }
  35460. return this._indexBuffer;
  35461. };
  35462. /** @ignore */
  35463. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  35464. if (effect === void 0) { effect = null; }
  35465. if (!effect || !this._vertexArrayObjects) {
  35466. return;
  35467. }
  35468. if (this._vertexArrayObjects[effect.key]) {
  35469. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  35470. delete this._vertexArrayObjects[effect.key];
  35471. }
  35472. };
  35473. /**
  35474. * Release the associated resources for a specific mesh
  35475. * @param mesh defines the source mesh
  35476. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  35477. */
  35478. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35479. var meshes = this._meshes;
  35480. var index = meshes.indexOf(mesh);
  35481. if (index === -1) {
  35482. return;
  35483. }
  35484. meshes.splice(index, 1);
  35485. mesh._geometry = null;
  35486. if (meshes.length === 0 && shouldDispose) {
  35487. this.dispose();
  35488. }
  35489. };
  35490. /**
  35491. * Apply current geometry to a given mesh
  35492. * @param mesh defines the mesh to apply geometry to
  35493. */
  35494. Geometry.prototype.applyToMesh = function (mesh) {
  35495. if (mesh._geometry === this) {
  35496. return;
  35497. }
  35498. var previousGeometry = mesh._geometry;
  35499. if (previousGeometry) {
  35500. previousGeometry.releaseForMesh(mesh);
  35501. }
  35502. var meshes = this._meshes;
  35503. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35504. mesh._geometry = this;
  35505. this._scene.pushGeometry(this);
  35506. meshes.push(mesh);
  35507. if (this.isReady()) {
  35508. this._applyToMesh(mesh);
  35509. }
  35510. else {
  35511. mesh._boundingInfo = this._boundingInfo;
  35512. }
  35513. };
  35514. Geometry.prototype.updateExtend = function (data, stride) {
  35515. if (data === void 0) { data = null; }
  35516. if (!data) {
  35517. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35518. }
  35519. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35520. };
  35521. Geometry.prototype._applyToMesh = function (mesh) {
  35522. var numOfMeshes = this._meshes.length;
  35523. // vertexBuffers
  35524. for (var kind in this._vertexBuffers) {
  35525. if (numOfMeshes === 1) {
  35526. this._vertexBuffers[kind].create();
  35527. }
  35528. var buffer = this._vertexBuffers[kind].getBuffer();
  35529. if (buffer)
  35530. buffer.references = numOfMeshes;
  35531. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35532. if (!this._extend) {
  35533. this.updateExtend(this._vertexBuffers[kind].getData());
  35534. }
  35535. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35536. mesh._createGlobalSubMesh(false);
  35537. //bounding info was just created again, world matrix should be applied again.
  35538. mesh._updateBoundingInfo();
  35539. }
  35540. }
  35541. // indexBuffer
  35542. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35543. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35544. }
  35545. if (this._indexBuffer) {
  35546. this._indexBuffer.references = numOfMeshes;
  35547. }
  35548. };
  35549. Geometry.prototype.notifyUpdate = function (kind) {
  35550. if (this.onGeometryUpdated) {
  35551. this.onGeometryUpdated(this, kind);
  35552. }
  35553. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35554. var mesh = _a[_i];
  35555. mesh._markSubMeshesAsAttributesDirty();
  35556. }
  35557. };
  35558. /**
  35559. * Load the geometry if it was flagged as delay loaded
  35560. * @param scene defines the hosting scene
  35561. * @param onLoaded defines a callback called when the geometry is loaded
  35562. */
  35563. Geometry.prototype.load = function (scene, onLoaded) {
  35564. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35565. return;
  35566. }
  35567. if (this.isReady()) {
  35568. if (onLoaded) {
  35569. onLoaded();
  35570. }
  35571. return;
  35572. }
  35573. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35574. this._queueLoad(scene, onLoaded);
  35575. };
  35576. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35577. var _this = this;
  35578. if (!this.delayLoadingFile) {
  35579. return;
  35580. }
  35581. scene._addPendingData(this);
  35582. scene._loadFile(this.delayLoadingFile, function (data) {
  35583. if (!_this._delayLoadingFunction) {
  35584. return;
  35585. }
  35586. _this._delayLoadingFunction(JSON.parse(data), _this);
  35587. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35588. _this._delayInfo = [];
  35589. scene._removePendingData(_this);
  35590. var meshes = _this._meshes;
  35591. var numOfMeshes = meshes.length;
  35592. for (var index = 0; index < numOfMeshes; index++) {
  35593. _this._applyToMesh(meshes[index]);
  35594. }
  35595. if (onLoaded) {
  35596. onLoaded();
  35597. }
  35598. }, undefined, true);
  35599. };
  35600. /**
  35601. * Invert the geometry to move from a right handed system to a left handed one.
  35602. */
  35603. Geometry.prototype.toLeftHanded = function () {
  35604. // Flip faces
  35605. var tIndices = this.getIndices(false);
  35606. if (tIndices != null && tIndices.length > 0) {
  35607. for (var i = 0; i < tIndices.length; i += 3) {
  35608. var tTemp = tIndices[i + 0];
  35609. tIndices[i + 0] = tIndices[i + 2];
  35610. tIndices[i + 2] = tTemp;
  35611. }
  35612. this.setIndices(tIndices);
  35613. }
  35614. // Negate position.z
  35615. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35616. if (tPositions != null && tPositions.length > 0) {
  35617. for (var i = 0; i < tPositions.length; i += 3) {
  35618. tPositions[i + 2] = -tPositions[i + 2];
  35619. }
  35620. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35621. }
  35622. // Negate normal.z
  35623. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35624. if (tNormals != null && tNormals.length > 0) {
  35625. for (var i = 0; i < tNormals.length; i += 3) {
  35626. tNormals[i + 2] = -tNormals[i + 2];
  35627. }
  35628. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35629. }
  35630. };
  35631. // Cache
  35632. /** @ignore */
  35633. Geometry.prototype._resetPointsArrayCache = function () {
  35634. this._positions = null;
  35635. };
  35636. /** @ignore */
  35637. Geometry.prototype._generatePointsArray = function () {
  35638. if (this._positions)
  35639. return true;
  35640. this._positions = [];
  35641. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35642. if (!data) {
  35643. return false;
  35644. }
  35645. for (var index = 0; index < data.length; index += 3) {
  35646. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35647. }
  35648. return true;
  35649. };
  35650. /**
  35651. * Gets a value indicating if the geometry is disposed
  35652. * @returns true if the geometry was disposed
  35653. */
  35654. Geometry.prototype.isDisposed = function () {
  35655. return this._isDisposed;
  35656. };
  35657. Geometry.prototype._disposeVertexArrayObjects = function () {
  35658. if (this._vertexArrayObjects) {
  35659. for (var kind in this._vertexArrayObjects) {
  35660. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35661. }
  35662. this._vertexArrayObjects = {};
  35663. }
  35664. };
  35665. /**
  35666. * Free all associated resources
  35667. */
  35668. Geometry.prototype.dispose = function () {
  35669. var meshes = this._meshes;
  35670. var numOfMeshes = meshes.length;
  35671. var index;
  35672. for (index = 0; index < numOfMeshes; index++) {
  35673. this.releaseForMesh(meshes[index]);
  35674. }
  35675. this._meshes = [];
  35676. this._disposeVertexArrayObjects();
  35677. for (var kind in this._vertexBuffers) {
  35678. this._vertexBuffers[kind].dispose();
  35679. }
  35680. this._vertexBuffers = {};
  35681. this._totalVertices = 0;
  35682. if (this._indexBuffer) {
  35683. this._engine._releaseBuffer(this._indexBuffer);
  35684. }
  35685. this._indexBuffer = null;
  35686. this._indices = [];
  35687. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35688. this.delayLoadingFile = null;
  35689. this._delayLoadingFunction = null;
  35690. this._delayInfo = [];
  35691. this._boundingInfo = null;
  35692. this._scene.removeGeometry(this);
  35693. this._isDisposed = true;
  35694. };
  35695. /**
  35696. * Clone the current geometry into a new geometry
  35697. * @param id defines the unique ID of the new geometry
  35698. * @returns a new geometry object
  35699. */
  35700. Geometry.prototype.copy = function (id) {
  35701. var vertexData = new BABYLON.VertexData();
  35702. vertexData.indices = [];
  35703. var indices = this.getIndices();
  35704. if (indices) {
  35705. for (var index = 0; index < indices.length; index++) {
  35706. vertexData.indices.push(indices[index]);
  35707. }
  35708. }
  35709. var updatable = false;
  35710. var stopChecking = false;
  35711. var kind;
  35712. for (kind in this._vertexBuffers) {
  35713. // using slice() to make a copy of the array and not just reference it
  35714. var data = this.getVerticesData(kind);
  35715. if (data instanceof Float32Array) {
  35716. vertexData.set(new Float32Array(data), kind);
  35717. }
  35718. else {
  35719. vertexData.set(data.slice(0), kind);
  35720. }
  35721. if (!stopChecking) {
  35722. var vb = this.getVertexBuffer(kind);
  35723. if (vb) {
  35724. updatable = vb.isUpdatable();
  35725. stopChecking = !updatable;
  35726. }
  35727. }
  35728. }
  35729. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35730. geometry.delayLoadState = this.delayLoadState;
  35731. geometry.delayLoadingFile = this.delayLoadingFile;
  35732. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35733. for (kind in this._delayInfo) {
  35734. geometry._delayInfo = geometry._delayInfo || [];
  35735. geometry._delayInfo.push(kind);
  35736. }
  35737. // Bounding info
  35738. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35739. return geometry;
  35740. };
  35741. /**
  35742. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35743. * @return a JSON representation of the current geometry data (without the vertices data)
  35744. */
  35745. Geometry.prototype.serialize = function () {
  35746. var serializationObject = {};
  35747. serializationObject.id = this.id;
  35748. serializationObject.updatable = this._updatable;
  35749. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35750. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35751. }
  35752. return serializationObject;
  35753. };
  35754. Geometry.prototype.toNumberArray = function (origin) {
  35755. if (Array.isArray(origin)) {
  35756. return origin;
  35757. }
  35758. else {
  35759. return Array.prototype.slice.call(origin);
  35760. }
  35761. };
  35762. /**
  35763. * Serialize all vertices data into a JSON oject
  35764. * @returns a JSON representation of the current geometry data
  35765. */
  35766. Geometry.prototype.serializeVerticeData = function () {
  35767. var serializationObject = this.serialize();
  35768. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35769. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35770. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35771. serializationObject.positions._updatable = true;
  35772. }
  35773. }
  35774. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35775. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35776. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35777. serializationObject.normals._updatable = true;
  35778. }
  35779. }
  35780. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35781. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35782. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35783. serializationObject.tangets._updatable = true;
  35784. }
  35785. }
  35786. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35787. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  35788. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  35789. serializationObject.uvs._updatable = true;
  35790. }
  35791. }
  35792. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35793. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  35794. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  35795. serializationObject.uv2s._updatable = true;
  35796. }
  35797. }
  35798. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35799. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  35800. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  35801. serializationObject.uv3s._updatable = true;
  35802. }
  35803. }
  35804. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35805. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  35806. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  35807. serializationObject.uv4s._updatable = true;
  35808. }
  35809. }
  35810. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35811. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  35812. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  35813. serializationObject.uv5s._updatable = true;
  35814. }
  35815. }
  35816. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35817. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  35818. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  35819. serializationObject.uv6s._updatable = true;
  35820. }
  35821. }
  35822. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35823. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  35824. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  35825. serializationObject.colors._updatable = true;
  35826. }
  35827. }
  35828. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35829. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  35830. serializationObject.matricesIndices._isExpanded = true;
  35831. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35832. serializationObject.matricesIndices._updatable = true;
  35833. }
  35834. }
  35835. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35836. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  35837. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35838. serializationObject.matricesWeights._updatable = true;
  35839. }
  35840. }
  35841. serializationObject.indices = this.toNumberArray(this.getIndices());
  35842. return serializationObject;
  35843. };
  35844. // Statics
  35845. /**
  35846. * Extracts a clone of a mesh geometry
  35847. * @param mesh defines the source mesh
  35848. * @param id defines the unique ID of the new geometry object
  35849. * @returns the new geometry object
  35850. */
  35851. Geometry.ExtractFromMesh = function (mesh, id) {
  35852. var geometry = mesh._geometry;
  35853. if (!geometry) {
  35854. return null;
  35855. }
  35856. return geometry.copy(id);
  35857. };
  35858. /**
  35859. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35860. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35861. * Be aware Math.random() could cause collisions, but:
  35862. * "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"
  35863. * @returns a string containing a new GUID
  35864. */
  35865. Geometry.RandomId = function () {
  35866. return BABYLON.Tools.RandomId();
  35867. };
  35868. /** @ignore */
  35869. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  35870. var scene = mesh.getScene();
  35871. // Geometry
  35872. var geometryId = parsedGeometry.geometryId;
  35873. if (geometryId) {
  35874. var geometry = scene.getGeometryByID(geometryId);
  35875. if (geometry) {
  35876. geometry.applyToMesh(mesh);
  35877. }
  35878. }
  35879. else if (parsedGeometry instanceof ArrayBuffer) {
  35880. var binaryInfo = mesh._binaryInfo;
  35881. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  35882. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  35883. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  35884. }
  35885. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  35886. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  35887. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  35888. }
  35889. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  35890. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  35891. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  35892. }
  35893. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  35894. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  35895. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  35896. }
  35897. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  35898. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  35899. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  35900. }
  35901. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  35902. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  35903. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  35904. }
  35905. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  35906. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  35907. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  35908. }
  35909. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  35910. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  35911. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  35912. }
  35913. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  35914. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  35915. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  35916. }
  35917. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  35918. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  35919. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  35920. }
  35921. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  35922. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  35923. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  35924. }
  35925. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  35926. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  35927. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  35928. }
  35929. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  35930. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  35931. mesh.setIndices(indicesData, null);
  35932. }
  35933. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  35934. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  35935. mesh.subMeshes = [];
  35936. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  35937. var materialIndex = subMeshesData[(i * 5) + 0];
  35938. var verticesStart = subMeshesData[(i * 5) + 1];
  35939. var verticesCount = subMeshesData[(i * 5) + 2];
  35940. var indexStart = subMeshesData[(i * 5) + 3];
  35941. var indexCount = subMeshesData[(i * 5) + 4];
  35942. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  35943. }
  35944. }
  35945. }
  35946. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  35947. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  35948. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  35949. if (parsedGeometry.tangents) {
  35950. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  35951. }
  35952. if (parsedGeometry.uvs) {
  35953. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  35954. }
  35955. if (parsedGeometry.uvs2) {
  35956. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  35957. }
  35958. if (parsedGeometry.uvs3) {
  35959. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  35960. }
  35961. if (parsedGeometry.uvs4) {
  35962. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  35963. }
  35964. if (parsedGeometry.uvs5) {
  35965. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  35966. }
  35967. if (parsedGeometry.uvs6) {
  35968. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  35969. }
  35970. if (parsedGeometry.colors) {
  35971. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  35972. }
  35973. if (parsedGeometry.matricesIndices) {
  35974. if (!parsedGeometry.matricesIndices._isExpanded) {
  35975. var floatIndices = [];
  35976. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  35977. var matricesIndex = parsedGeometry.matricesIndices[i];
  35978. floatIndices.push(matricesIndex & 0x000000FF);
  35979. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35980. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35981. floatIndices.push(matricesIndex >> 24);
  35982. }
  35983. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  35984. }
  35985. else {
  35986. delete parsedGeometry.matricesIndices._isExpanded;
  35987. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  35988. }
  35989. }
  35990. if (parsedGeometry.matricesIndicesExtra) {
  35991. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  35992. var floatIndices = [];
  35993. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  35994. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  35995. floatIndices.push(matricesIndex & 0x000000FF);
  35996. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35997. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35998. floatIndices.push(matricesIndex >> 24);
  35999. }
  36000. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  36001. }
  36002. else {
  36003. delete parsedGeometry.matricesIndices._isExpanded;
  36004. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  36005. }
  36006. }
  36007. if (parsedGeometry.matricesWeights) {
  36008. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  36009. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  36010. }
  36011. if (parsedGeometry.matricesWeightsExtra) {
  36012. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  36013. }
  36014. mesh.setIndices(parsedGeometry.indices, null);
  36015. }
  36016. // SubMeshes
  36017. if (parsedGeometry.subMeshes) {
  36018. mesh.subMeshes = [];
  36019. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  36020. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  36021. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  36022. }
  36023. }
  36024. // Flat shading
  36025. if (mesh._shouldGenerateFlatShading) {
  36026. mesh.convertToFlatShadedMesh();
  36027. delete mesh._shouldGenerateFlatShading;
  36028. }
  36029. // Update
  36030. mesh.computeWorldMatrix(true);
  36031. // Octree
  36032. var sceneOctree = scene.selectionOctree;
  36033. if (sceneOctree !== undefined && sceneOctree !== null) {
  36034. sceneOctree.addMesh(mesh);
  36035. }
  36036. };
  36037. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  36038. var epsilon = 1e-3;
  36039. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  36040. return;
  36041. }
  36042. var noInfluenceBoneIndex = 0.0;
  36043. if (parsedGeometry.skeletonId > -1) {
  36044. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  36045. if (!skeleton) {
  36046. return;
  36047. }
  36048. noInfluenceBoneIndex = skeleton.bones.length;
  36049. }
  36050. else {
  36051. return;
  36052. }
  36053. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  36054. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36055. var matricesWeights = parsedGeometry.matricesWeights;
  36056. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  36057. var influencers = parsedGeometry.numBoneInfluencer;
  36058. var size = matricesWeights.length;
  36059. for (var i = 0; i < size; i += 4) {
  36060. var weight = 0.0;
  36061. var firstZeroWeight = -1;
  36062. for (var j = 0; j < 4; j++) {
  36063. var w = matricesWeights[i + j];
  36064. weight += w;
  36065. if (w < epsilon && firstZeroWeight < 0) {
  36066. firstZeroWeight = j;
  36067. }
  36068. }
  36069. if (matricesWeightsExtra) {
  36070. for (var j = 0; j < 4; j++) {
  36071. var w = matricesWeightsExtra[i + j];
  36072. weight += w;
  36073. if (w < epsilon && firstZeroWeight < 0) {
  36074. firstZeroWeight = j + 4;
  36075. }
  36076. }
  36077. }
  36078. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  36079. firstZeroWeight = influencers - 1;
  36080. }
  36081. if (weight > epsilon) {
  36082. var mweight = 1.0 / weight;
  36083. for (var j = 0; j < 4; j++) {
  36084. matricesWeights[i + j] *= mweight;
  36085. }
  36086. if (matricesWeightsExtra) {
  36087. for (var j = 0; j < 4; j++) {
  36088. matricesWeightsExtra[i + j] *= mweight;
  36089. }
  36090. }
  36091. }
  36092. else {
  36093. if (firstZeroWeight >= 4) {
  36094. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  36095. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  36096. }
  36097. else {
  36098. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  36099. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  36100. }
  36101. }
  36102. }
  36103. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  36104. if (parsedGeometry.matricesWeightsExtra) {
  36105. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  36106. }
  36107. };
  36108. /**
  36109. * Create a new geometry from persisted data (Using .babylon file format)
  36110. * @param parsedVertexData defines the persisted data
  36111. * @param scene defines the hosting scene
  36112. * @param rootUrl defines the root url to use to load assets (like delayed data)
  36113. * @returns the new geometry object
  36114. */
  36115. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  36116. if (scene.getGeometryByID(parsedVertexData.id)) {
  36117. return null; // null since geometry could be something else than a box...
  36118. }
  36119. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  36120. if (BABYLON.Tags) {
  36121. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  36122. }
  36123. if (parsedVertexData.delayLoadingFile) {
  36124. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  36125. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  36126. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  36127. geometry._delayInfo = [];
  36128. if (parsedVertexData.hasUVs) {
  36129. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  36130. }
  36131. if (parsedVertexData.hasUVs2) {
  36132. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  36133. }
  36134. if (parsedVertexData.hasUVs3) {
  36135. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  36136. }
  36137. if (parsedVertexData.hasUVs4) {
  36138. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  36139. }
  36140. if (parsedVertexData.hasUVs5) {
  36141. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  36142. }
  36143. if (parsedVertexData.hasUVs6) {
  36144. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  36145. }
  36146. if (parsedVertexData.hasColors) {
  36147. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  36148. }
  36149. if (parsedVertexData.hasMatricesIndices) {
  36150. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36151. }
  36152. if (parsedVertexData.hasMatricesWeights) {
  36153. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36154. }
  36155. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  36156. }
  36157. else {
  36158. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  36159. }
  36160. scene.pushGeometry(geometry, true);
  36161. return geometry;
  36162. };
  36163. return Geometry;
  36164. }());
  36165. BABYLON.Geometry = Geometry;
  36166. // Primitives
  36167. /// Abstract class
  36168. /**
  36169. * Abstract class used to provide common services for all typed geometries
  36170. */
  36171. var _PrimitiveGeometry = /** @class */ (function (_super) {
  36172. __extends(_PrimitiveGeometry, _super);
  36173. /**
  36174. * Creates a new typed geometry
  36175. * @param id defines the unique ID of the geometry
  36176. * @param scene defines the hosting scene
  36177. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36178. * @param mesh defines the hosting mesh (can be null)
  36179. */
  36180. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  36181. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  36182. if (mesh === void 0) { mesh = null; }
  36183. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  36184. _this._canBeRegenerated = _canBeRegenerated;
  36185. _this._beingRegenerated = true;
  36186. _this.regenerate();
  36187. _this._beingRegenerated = false;
  36188. return _this;
  36189. }
  36190. /**
  36191. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  36192. * @returns true if the geometry can be regenerated
  36193. */
  36194. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  36195. return this._canBeRegenerated;
  36196. };
  36197. /**
  36198. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  36199. */
  36200. _PrimitiveGeometry.prototype.regenerate = function () {
  36201. if (!this._canBeRegenerated) {
  36202. return;
  36203. }
  36204. this._beingRegenerated = true;
  36205. this.setAllVerticesData(this._regenerateVertexData(), false);
  36206. this._beingRegenerated = false;
  36207. };
  36208. /**
  36209. * Clone the geometry
  36210. * @param id defines the unique ID of the new geometry
  36211. * @returns the new geometry
  36212. */
  36213. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  36214. return _super.prototype.copy.call(this, id);
  36215. };
  36216. // overrides
  36217. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  36218. if (!this._beingRegenerated) {
  36219. return;
  36220. }
  36221. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  36222. };
  36223. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  36224. if (!this._beingRegenerated) {
  36225. return;
  36226. }
  36227. _super.prototype.setVerticesData.call(this, kind, data, false);
  36228. };
  36229. // to override
  36230. /** @ignore */
  36231. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  36232. throw new Error("Abstract method");
  36233. };
  36234. _PrimitiveGeometry.prototype.copy = function (id) {
  36235. throw new Error("Must be overriden in sub-classes.");
  36236. };
  36237. _PrimitiveGeometry.prototype.serialize = function () {
  36238. var serializationObject = _super.prototype.serialize.call(this);
  36239. serializationObject.canBeRegenerated = this.canBeRegenerated();
  36240. return serializationObject;
  36241. };
  36242. return _PrimitiveGeometry;
  36243. }(Geometry));
  36244. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  36245. /**
  36246. * Creates a ribbon geometry
  36247. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  36248. */
  36249. var RibbonGeometry = /** @class */ (function (_super) {
  36250. __extends(RibbonGeometry, _super);
  36251. /**
  36252. * Creates a ribbon geometry
  36253. * @param id defines the unique ID of the geometry
  36254. * @param scene defines the hosting scene
  36255. * @param pathArray defines the array of paths to use
  36256. * @param closeArray defines if the last path and the first path must be joined
  36257. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  36258. * @param offset defines the offset between points
  36259. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36260. * @param mesh defines the hosting mesh (can be null)
  36261. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36262. */
  36263. function RibbonGeometry(id, scene,
  36264. /**
  36265. * Defines the array of paths to use
  36266. */
  36267. pathArray,
  36268. /**
  36269. * Defines if the last and first points of each path in your pathArray must be joined
  36270. */
  36271. closeArray,
  36272. /**
  36273. * Defines if the last and first points of each path in your pathArray must be joined
  36274. */
  36275. closePath,
  36276. /**
  36277. * Defines the offset between points
  36278. */
  36279. offset, canBeRegenerated, mesh,
  36280. /**
  36281. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36282. */
  36283. side) {
  36284. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36285. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36286. _this.pathArray = pathArray;
  36287. _this.closeArray = closeArray;
  36288. _this.closePath = closePath;
  36289. _this.offset = offset;
  36290. _this.side = side;
  36291. return _this;
  36292. }
  36293. /** @ignore */
  36294. RibbonGeometry.prototype._regenerateVertexData = function () {
  36295. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  36296. };
  36297. RibbonGeometry.prototype.copy = function (id) {
  36298. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  36299. };
  36300. return RibbonGeometry;
  36301. }(_PrimitiveGeometry));
  36302. BABYLON.RibbonGeometry = RibbonGeometry;
  36303. /**
  36304. * Creates a box geometry
  36305. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  36306. */
  36307. var BoxGeometry = /** @class */ (function (_super) {
  36308. __extends(BoxGeometry, _super);
  36309. /**
  36310. * Creates a box geometry
  36311. * @param id defines the unique ID of the geometry
  36312. * @param scene defines the hosting scene
  36313. * @param size defines the zise of the box (width, height and depth are the same)
  36314. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36315. * @param mesh defines the hosting mesh (can be null)
  36316. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36317. */
  36318. function BoxGeometry(id, scene,
  36319. /**
  36320. * Defines the zise of the box (width, height and depth are the same)
  36321. */
  36322. size, canBeRegenerated, mesh,
  36323. /**
  36324. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36325. */
  36326. side) {
  36327. if (mesh === void 0) { mesh = null; }
  36328. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36329. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36330. _this.size = size;
  36331. _this.side = side;
  36332. return _this;
  36333. }
  36334. BoxGeometry.prototype._regenerateVertexData = function () {
  36335. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  36336. };
  36337. BoxGeometry.prototype.copy = function (id) {
  36338. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  36339. };
  36340. BoxGeometry.prototype.serialize = function () {
  36341. var serializationObject = _super.prototype.serialize.call(this);
  36342. serializationObject.size = this.size;
  36343. return serializationObject;
  36344. };
  36345. BoxGeometry.Parse = function (parsedBox, scene) {
  36346. if (scene.getGeometryByID(parsedBox.id)) {
  36347. return null; // null since geometry could be something else than a box...
  36348. }
  36349. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  36350. if (BABYLON.Tags) {
  36351. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  36352. }
  36353. scene.pushGeometry(box, true);
  36354. return box;
  36355. };
  36356. return BoxGeometry;
  36357. }(_PrimitiveGeometry));
  36358. BABYLON.BoxGeometry = BoxGeometry;
  36359. /**
  36360. * Creates a sphere geometry
  36361. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  36362. */
  36363. var SphereGeometry = /** @class */ (function (_super) {
  36364. __extends(SphereGeometry, _super);
  36365. /**
  36366. * Create a new sphere geometry
  36367. * @param id defines the unique ID of the geometry
  36368. * @param scene defines the hosting scene
  36369. * @param segments defines the number of segments to use to create the sphere
  36370. * @param diameter defines the diameter of the sphere
  36371. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36372. * @param mesh defines the hosting mesh (can be null)
  36373. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36374. */
  36375. function SphereGeometry(id, scene,
  36376. /**
  36377. * Defines the number of segments to use to create the sphere
  36378. */
  36379. segments,
  36380. /**
  36381. * Defines the diameter of the sphere
  36382. */
  36383. diameter, canBeRegenerated, mesh,
  36384. /**
  36385. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36386. */
  36387. side) {
  36388. if (mesh === void 0) { mesh = null; }
  36389. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36390. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36391. _this.segments = segments;
  36392. _this.diameter = diameter;
  36393. _this.side = side;
  36394. return _this;
  36395. }
  36396. SphereGeometry.prototype._regenerateVertexData = function () {
  36397. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36398. };
  36399. SphereGeometry.prototype.copy = function (id) {
  36400. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36401. };
  36402. SphereGeometry.prototype.serialize = function () {
  36403. var serializationObject = _super.prototype.serialize.call(this);
  36404. serializationObject.segments = this.segments;
  36405. serializationObject.diameter = this.diameter;
  36406. return serializationObject;
  36407. };
  36408. SphereGeometry.Parse = function (parsedSphere, scene) {
  36409. if (scene.getGeometryByID(parsedSphere.id)) {
  36410. return null; // null since geometry could be something else than a sphere...
  36411. }
  36412. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  36413. if (BABYLON.Tags) {
  36414. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  36415. }
  36416. scene.pushGeometry(sphere, true);
  36417. return sphere;
  36418. };
  36419. return SphereGeometry;
  36420. }(_PrimitiveGeometry));
  36421. BABYLON.SphereGeometry = SphereGeometry;
  36422. /**
  36423. * Creates a disc geometry
  36424. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  36425. */
  36426. var DiscGeometry = /** @class */ (function (_super) {
  36427. __extends(DiscGeometry, _super);
  36428. /**
  36429. * Creates a new disc geometry
  36430. * @param id defines the unique ID of the geometry
  36431. * @param scene defines the hosting scene
  36432. * @param radius defines the radius of the disc
  36433. * @param tessellation defines the tesselation factor to apply to the disc
  36434. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36435. * @param mesh defines the hosting mesh (can be null)
  36436. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36437. */
  36438. function DiscGeometry(id, scene,
  36439. /**
  36440. * Defines the radius of the disc
  36441. */
  36442. radius,
  36443. /**
  36444. * Defines the tesselation factor to apply to the disc
  36445. */
  36446. tessellation, canBeRegenerated, mesh,
  36447. /**
  36448. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36449. */
  36450. side) {
  36451. if (mesh === void 0) { mesh = null; }
  36452. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36453. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36454. _this.radius = radius;
  36455. _this.tessellation = tessellation;
  36456. _this.side = side;
  36457. return _this;
  36458. }
  36459. DiscGeometry.prototype._regenerateVertexData = function () {
  36460. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36461. };
  36462. DiscGeometry.prototype.copy = function (id) {
  36463. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36464. };
  36465. return DiscGeometry;
  36466. }(_PrimitiveGeometry));
  36467. BABYLON.DiscGeometry = DiscGeometry;
  36468. /**
  36469. * Creates a new cylinder geometry
  36470. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  36471. */
  36472. var CylinderGeometry = /** @class */ (function (_super) {
  36473. __extends(CylinderGeometry, _super);
  36474. /**
  36475. * Creates a new cylinder geometry
  36476. * @param id defines the unique ID of the geometry
  36477. * @param scene defines the hosting scene
  36478. * @param height defines the height of the cylinder
  36479. * @param diameterTop defines the diameter of the cylinder's top cap
  36480. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  36481. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  36482. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  36483. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36484. * @param mesh defines the hosting mesh (can be null)
  36485. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36486. */
  36487. function CylinderGeometry(id, scene,
  36488. /**
  36489. * Defines the height of the cylinder
  36490. */
  36491. height,
  36492. /**
  36493. * Defines the diameter of the cylinder's top cap
  36494. */
  36495. diameterTop,
  36496. /**
  36497. * Defines the diameter of the cylinder's bottom cap
  36498. */
  36499. diameterBottom,
  36500. /**
  36501. * Defines the tessellation factor to apply to the cylinder
  36502. */
  36503. tessellation,
  36504. /**
  36505. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36506. */
  36507. subdivisions, canBeRegenerated, mesh,
  36508. /**
  36509. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36510. */
  36511. side) {
  36512. if (subdivisions === void 0) { subdivisions = 1; }
  36513. if (mesh === void 0) { mesh = null; }
  36514. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36515. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36516. _this.height = height;
  36517. _this.diameterTop = diameterTop;
  36518. _this.diameterBottom = diameterBottom;
  36519. _this.tessellation = tessellation;
  36520. _this.subdivisions = subdivisions;
  36521. _this.side = side;
  36522. return _this;
  36523. }
  36524. CylinderGeometry.prototype._regenerateVertexData = function () {
  36525. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36526. };
  36527. CylinderGeometry.prototype.copy = function (id) {
  36528. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36529. };
  36530. CylinderGeometry.prototype.serialize = function () {
  36531. var serializationObject = _super.prototype.serialize.call(this);
  36532. serializationObject.height = this.height;
  36533. serializationObject.diameterTop = this.diameterTop;
  36534. serializationObject.diameterBottom = this.diameterBottom;
  36535. serializationObject.tessellation = this.tessellation;
  36536. return serializationObject;
  36537. };
  36538. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36539. if (scene.getGeometryByID(parsedCylinder.id)) {
  36540. return null; // null since geometry could be something else than a cylinder...
  36541. }
  36542. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36543. if (BABYLON.Tags) {
  36544. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36545. }
  36546. scene.pushGeometry(cylinder, true);
  36547. return cylinder;
  36548. };
  36549. return CylinderGeometry;
  36550. }(_PrimitiveGeometry));
  36551. BABYLON.CylinderGeometry = CylinderGeometry;
  36552. /**
  36553. * Creates a new torus geometry
  36554. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36555. */
  36556. var TorusGeometry = /** @class */ (function (_super) {
  36557. __extends(TorusGeometry, _super);
  36558. /**
  36559. * Creates a new torus geometry
  36560. * @param id defines the unique ID of the geometry
  36561. * @param scene defines the hosting scene
  36562. * @param diameter defines the diameter of the torus
  36563. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36564. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36565. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36566. * @param mesh defines the hosting mesh (can be null)
  36567. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36568. */
  36569. function TorusGeometry(id, scene,
  36570. /**
  36571. * Defines the diameter of the torus
  36572. */
  36573. diameter,
  36574. /**
  36575. * Defines the thickness of the torus (ie. internal diameter)
  36576. */
  36577. thickness,
  36578. /**
  36579. * Defines the tesselation factor to apply to the torus
  36580. */
  36581. tessellation, canBeRegenerated, mesh,
  36582. /**
  36583. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36584. */
  36585. side) {
  36586. if (mesh === void 0) { mesh = null; }
  36587. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36588. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36589. _this.diameter = diameter;
  36590. _this.thickness = thickness;
  36591. _this.tessellation = tessellation;
  36592. _this.side = side;
  36593. return _this;
  36594. }
  36595. TorusGeometry.prototype._regenerateVertexData = function () {
  36596. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36597. };
  36598. TorusGeometry.prototype.copy = function (id) {
  36599. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36600. };
  36601. TorusGeometry.prototype.serialize = function () {
  36602. var serializationObject = _super.prototype.serialize.call(this);
  36603. serializationObject.diameter = this.diameter;
  36604. serializationObject.thickness = this.thickness;
  36605. serializationObject.tessellation = this.tessellation;
  36606. return serializationObject;
  36607. };
  36608. TorusGeometry.Parse = function (parsedTorus, scene) {
  36609. if (scene.getGeometryByID(parsedTorus.id)) {
  36610. return null; // null since geometry could be something else than a torus...
  36611. }
  36612. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36613. if (BABYLON.Tags) {
  36614. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36615. }
  36616. scene.pushGeometry(torus, true);
  36617. return torus;
  36618. };
  36619. return TorusGeometry;
  36620. }(_PrimitiveGeometry));
  36621. BABYLON.TorusGeometry = TorusGeometry;
  36622. /**
  36623. * Creates a new ground geometry
  36624. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36625. */
  36626. var GroundGeometry = /** @class */ (function (_super) {
  36627. __extends(GroundGeometry, _super);
  36628. /**
  36629. * Creates a new ground geometry
  36630. * @param id defines the unique ID of the geometry
  36631. * @param scene defines the hosting scene
  36632. * @param width defines the width of the ground
  36633. * @param height defines the height of the ground
  36634. * @param subdivisions defines the subdivisions to apply to the ground
  36635. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36636. * @param mesh defines the hosting mesh (can be null)
  36637. */
  36638. function GroundGeometry(id, scene,
  36639. /**
  36640. * Defines the width of the ground
  36641. */
  36642. width,
  36643. /**
  36644. * Defines the height of the ground
  36645. */
  36646. height,
  36647. /**
  36648. * Defines the subdivisions to apply to the ground
  36649. */
  36650. subdivisions, canBeRegenerated, mesh) {
  36651. if (mesh === void 0) { mesh = null; }
  36652. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36653. _this.width = width;
  36654. _this.height = height;
  36655. _this.subdivisions = subdivisions;
  36656. return _this;
  36657. }
  36658. GroundGeometry.prototype._regenerateVertexData = function () {
  36659. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36660. };
  36661. GroundGeometry.prototype.copy = function (id) {
  36662. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36663. };
  36664. GroundGeometry.prototype.serialize = function () {
  36665. var serializationObject = _super.prototype.serialize.call(this);
  36666. serializationObject.width = this.width;
  36667. serializationObject.height = this.height;
  36668. serializationObject.subdivisions = this.subdivisions;
  36669. return serializationObject;
  36670. };
  36671. GroundGeometry.Parse = function (parsedGround, scene) {
  36672. if (scene.getGeometryByID(parsedGround.id)) {
  36673. return null; // null since geometry could be something else than a ground...
  36674. }
  36675. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36676. if (BABYLON.Tags) {
  36677. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36678. }
  36679. scene.pushGeometry(ground, true);
  36680. return ground;
  36681. };
  36682. return GroundGeometry;
  36683. }(_PrimitiveGeometry));
  36684. BABYLON.GroundGeometry = GroundGeometry;
  36685. /**
  36686. * Creates a tiled ground geometry
  36687. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36688. */
  36689. var TiledGroundGeometry = /** @class */ (function (_super) {
  36690. __extends(TiledGroundGeometry, _super);
  36691. /**
  36692. * Creates a tiled ground geometry
  36693. * @param id defines the unique ID of the geometry
  36694. * @param scene defines the hosting scene
  36695. * @param xmin defines the minimum value on X axis
  36696. * @param zmin defines the minimum value on Z axis
  36697. * @param xmax defines the maximum value on X axis
  36698. * @param zmax defines the maximum value on Z axis
  36699. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36700. * @param precision defines the precision to use when computing the tiles
  36701. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36702. * @param mesh defines the hosting mesh (can be null)
  36703. */
  36704. function TiledGroundGeometry(id, scene,
  36705. /**
  36706. * Defines the minimum value on X axis
  36707. */
  36708. xmin,
  36709. /**
  36710. * Defines the minimum value on Z axis
  36711. */
  36712. zmin,
  36713. /**
  36714. * Defines the maximum value on X axis
  36715. */
  36716. xmax,
  36717. /**
  36718. * Defines the maximum value on Z axis
  36719. */
  36720. zmax,
  36721. /**
  36722. * Defines the subdivisions to apply to the ground
  36723. */
  36724. subdivisions,
  36725. /**
  36726. * Defines the precision to use when computing the tiles
  36727. */
  36728. precision, canBeRegenerated, mesh) {
  36729. if (mesh === void 0) { mesh = null; }
  36730. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36731. _this.xmin = xmin;
  36732. _this.zmin = zmin;
  36733. _this.xmax = xmax;
  36734. _this.zmax = zmax;
  36735. _this.subdivisions = subdivisions;
  36736. _this.precision = precision;
  36737. return _this;
  36738. }
  36739. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36740. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36741. };
  36742. TiledGroundGeometry.prototype.copy = function (id) {
  36743. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36744. };
  36745. return TiledGroundGeometry;
  36746. }(_PrimitiveGeometry));
  36747. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36748. /**
  36749. * Creates a plane geometry
  36750. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36751. */
  36752. var PlaneGeometry = /** @class */ (function (_super) {
  36753. __extends(PlaneGeometry, _super);
  36754. /**
  36755. * Creates a plane geometry
  36756. * @param id defines the unique ID of the geometry
  36757. * @param scene defines the hosting scene
  36758. * @param size defines the size of the plane (width === height)
  36759. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36760. * @param mesh defines the hosting mesh (can be null)
  36761. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36762. */
  36763. function PlaneGeometry(id, scene,
  36764. /**
  36765. * Defines the size of the plane (width === height)
  36766. */
  36767. size, canBeRegenerated, mesh,
  36768. /**
  36769. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36770. */
  36771. side) {
  36772. if (mesh === void 0) { mesh = null; }
  36773. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36774. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36775. _this.size = size;
  36776. _this.side = side;
  36777. return _this;
  36778. }
  36779. PlaneGeometry.prototype._regenerateVertexData = function () {
  36780. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36781. };
  36782. PlaneGeometry.prototype.copy = function (id) {
  36783. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36784. };
  36785. PlaneGeometry.prototype.serialize = function () {
  36786. var serializationObject = _super.prototype.serialize.call(this);
  36787. serializationObject.size = this.size;
  36788. return serializationObject;
  36789. };
  36790. PlaneGeometry.Parse = function (parsedPlane, scene) {
  36791. if (scene.getGeometryByID(parsedPlane.id)) {
  36792. return null; // null since geometry could be something else than a ground...
  36793. }
  36794. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36795. if (BABYLON.Tags) {
  36796. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36797. }
  36798. scene.pushGeometry(plane, true);
  36799. return plane;
  36800. };
  36801. return PlaneGeometry;
  36802. }(_PrimitiveGeometry));
  36803. BABYLON.PlaneGeometry = PlaneGeometry;
  36804. /**
  36805. * Creates a torus knot geometry
  36806. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  36807. */
  36808. var TorusKnotGeometry = /** @class */ (function (_super) {
  36809. __extends(TorusKnotGeometry, _super);
  36810. /**
  36811. * Creates a torus knot geometry
  36812. * @param id defines the unique ID of the geometry
  36813. * @param scene defines the hosting scene
  36814. * @param radius defines the radius of the torus knot
  36815. * @param tube defines the thickness of the torus knot tube
  36816. * @param radialSegments defines the number of radial segments
  36817. * @param tubularSegments defines the number of tubular segments
  36818. * @param p defines the first number of windings
  36819. * @param q defines the second number of windings
  36820. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36821. * @param mesh defines the hosting mesh (can be null)
  36822. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36823. */
  36824. function TorusKnotGeometry(id, scene,
  36825. /**
  36826. * Defines the radius of the torus knot
  36827. */
  36828. radius,
  36829. /**
  36830. * Defines the thickness of the torus knot tube
  36831. */
  36832. tube,
  36833. /**
  36834. * Defines the number of radial segments
  36835. */
  36836. radialSegments,
  36837. /**
  36838. * Defines the number of tubular segments
  36839. */
  36840. tubularSegments,
  36841. /**
  36842. * Defines the first number of windings
  36843. */
  36844. p,
  36845. /**
  36846. * Defines the second number of windings
  36847. */
  36848. q, canBeRegenerated, mesh,
  36849. /**
  36850. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36851. */
  36852. side) {
  36853. if (mesh === void 0) { mesh = null; }
  36854. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36855. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36856. _this.radius = radius;
  36857. _this.tube = tube;
  36858. _this.radialSegments = radialSegments;
  36859. _this.tubularSegments = tubularSegments;
  36860. _this.p = p;
  36861. _this.q = q;
  36862. _this.side = side;
  36863. return _this;
  36864. }
  36865. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  36866. 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 });
  36867. };
  36868. TorusKnotGeometry.prototype.copy = function (id) {
  36869. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  36870. };
  36871. TorusKnotGeometry.prototype.serialize = function () {
  36872. var serializationObject = _super.prototype.serialize.call(this);
  36873. serializationObject.radius = this.radius;
  36874. serializationObject.tube = this.tube;
  36875. serializationObject.radialSegments = this.radialSegments;
  36876. serializationObject.tubularSegments = this.tubularSegments;
  36877. serializationObject.p = this.p;
  36878. serializationObject.q = this.q;
  36879. return serializationObject;
  36880. };
  36881. ;
  36882. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  36883. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  36884. return null; // null since geometry could be something else than a ground...
  36885. }
  36886. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  36887. if (BABYLON.Tags) {
  36888. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  36889. }
  36890. scene.pushGeometry(torusKnot, true);
  36891. return torusKnot;
  36892. };
  36893. return TorusKnotGeometry;
  36894. }(_PrimitiveGeometry));
  36895. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  36896. //}
  36897. })(BABYLON || (BABYLON = {}));
  36898. //# sourceMappingURL=babylon.geometry.js.map
  36899. var BABYLON;
  36900. (function (BABYLON) {
  36901. /**
  36902. * PostProcessManager is used to manage one or more post processes or post process pipelines
  36903. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  36904. */
  36905. var PostProcessManager = /** @class */ (function () {
  36906. /**
  36907. * Creates a new instance of @see PostProcess
  36908. * @param scene The scene that the post process is associated with.
  36909. */
  36910. function PostProcessManager(scene) {
  36911. this._vertexBuffers = {};
  36912. this._scene = scene;
  36913. }
  36914. PostProcessManager.prototype._prepareBuffers = function () {
  36915. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  36916. return;
  36917. }
  36918. // VBO
  36919. var vertices = [];
  36920. vertices.push(1, 1);
  36921. vertices.push(-1, 1);
  36922. vertices.push(-1, -1);
  36923. vertices.push(1, -1);
  36924. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  36925. this._buildIndexBuffer();
  36926. };
  36927. PostProcessManager.prototype._buildIndexBuffer = function () {
  36928. // Indices
  36929. var indices = [];
  36930. indices.push(0);
  36931. indices.push(1);
  36932. indices.push(2);
  36933. indices.push(0);
  36934. indices.push(2);
  36935. indices.push(3);
  36936. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  36937. };
  36938. /**
  36939. * Rebuilds the vertex buffers of the manager.
  36940. */
  36941. PostProcessManager.prototype._rebuild = function () {
  36942. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36943. if (!vb) {
  36944. return;
  36945. }
  36946. vb._rebuild();
  36947. this._buildIndexBuffer();
  36948. };
  36949. // Methods
  36950. /**
  36951. * Prepares a frame to be run through a post process.
  36952. * @param sourceTexture The input texture to the post procesess. (default: null)
  36953. * @param postProcesses An array of post processes to be run. (default: null)
  36954. * @returns True if the post processes were able to be run.
  36955. */
  36956. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  36957. if (sourceTexture === void 0) { sourceTexture = null; }
  36958. if (postProcesses === void 0) { postProcesses = null; }
  36959. var camera = this._scene.activeCamera;
  36960. if (!camera) {
  36961. return false;
  36962. }
  36963. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  36964. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36965. return false;
  36966. }
  36967. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  36968. return true;
  36969. };
  36970. /**
  36971. * Manually render a set of post processes to a texture.
  36972. * @param postProcesses An array of post processes to be run.
  36973. * @param targetTexture The target texture to render to.
  36974. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  36975. */
  36976. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  36977. if (targetTexture === void 0) { targetTexture = null; }
  36978. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36979. var engine = this._scene.getEngine();
  36980. for (var index = 0; index < postProcesses.length; index++) {
  36981. if (index < postProcesses.length - 1) {
  36982. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  36983. }
  36984. else {
  36985. if (targetTexture) {
  36986. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  36987. }
  36988. else {
  36989. engine.restoreDefaultFramebuffer();
  36990. }
  36991. }
  36992. var pp = postProcesses[index];
  36993. var effect = pp.apply();
  36994. if (effect) {
  36995. pp.onBeforeRenderObservable.notifyObservers(effect);
  36996. // VBOs
  36997. this._prepareBuffers();
  36998. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36999. // Draw order
  37000. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  37001. pp.onAfterRenderObservable.notifyObservers(effect);
  37002. }
  37003. }
  37004. // Restore depth buffer
  37005. engine.setDepthBuffer(true);
  37006. engine.setDepthWrite(true);
  37007. };
  37008. /**
  37009. * Finalize the result of the output of the postprocesses.
  37010. * @param doNotPresent If true the result will not be displayed to the screen.
  37011. * @param targetTexture The target texture to render to.
  37012. * @param faceIndex The index of the face to bind the target texture to.
  37013. * @param postProcesses The array of post processes to render.
  37014. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  37015. */
  37016. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  37017. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  37018. var camera = this._scene.activeCamera;
  37019. if (!camera) {
  37020. return;
  37021. }
  37022. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  37023. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37024. return;
  37025. }
  37026. var engine = this._scene.getEngine();
  37027. for (var index = 0, len = postProcesses.length; index < len; index++) {
  37028. if (index < len - 1) {
  37029. postProcesses[index + 1].activate(camera, targetTexture);
  37030. }
  37031. else {
  37032. if (targetTexture) {
  37033. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  37034. }
  37035. else {
  37036. engine.restoreDefaultFramebuffer();
  37037. }
  37038. }
  37039. if (doNotPresent) {
  37040. break;
  37041. }
  37042. var pp = postProcesses[index];
  37043. var effect = pp.apply();
  37044. if (effect) {
  37045. pp.onBeforeRenderObservable.notifyObservers(effect);
  37046. // VBOs
  37047. this._prepareBuffers();
  37048. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37049. // Draw order
  37050. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  37051. pp.onAfterRenderObservable.notifyObservers(effect);
  37052. }
  37053. }
  37054. // Restore states
  37055. engine.setDepthBuffer(true);
  37056. engine.setDepthWrite(true);
  37057. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  37058. };
  37059. /**
  37060. * Disposes of the post process manager.
  37061. */
  37062. PostProcessManager.prototype.dispose = function () {
  37063. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37064. if (buffer) {
  37065. buffer.dispose();
  37066. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  37067. }
  37068. if (this._indexBuffer) {
  37069. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37070. this._indexBuffer = null;
  37071. }
  37072. };
  37073. return PostProcessManager;
  37074. }());
  37075. BABYLON.PostProcessManager = PostProcessManager;
  37076. })(BABYLON || (BABYLON = {}));
  37077. //# sourceMappingURL=babylon.postProcessManager.js.map
  37078. var BABYLON;
  37079. (function (BABYLON) {
  37080. /**
  37081. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  37082. */
  37083. var PerformanceMonitor = /** @class */ (function () {
  37084. /**
  37085. * constructor
  37086. * @param frameSampleSize The number of samples required to saturate the sliding window
  37087. */
  37088. function PerformanceMonitor(frameSampleSize) {
  37089. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  37090. this._enabled = true;
  37091. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  37092. }
  37093. /**
  37094. * Samples current frame
  37095. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  37096. */
  37097. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  37098. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  37099. if (!this._enabled)
  37100. return;
  37101. if (this._lastFrameTimeMs != null) {
  37102. var dt = timeMs - this._lastFrameTimeMs;
  37103. this._rollingFrameTime.add(dt);
  37104. }
  37105. this._lastFrameTimeMs = timeMs;
  37106. };
  37107. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  37108. /**
  37109. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  37110. * @return Average frame time in milliseconds
  37111. */
  37112. get: function () {
  37113. return this._rollingFrameTime.average;
  37114. },
  37115. enumerable: true,
  37116. configurable: true
  37117. });
  37118. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  37119. /**
  37120. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  37121. * @return Frame time variance in milliseconds squared
  37122. */
  37123. get: function () {
  37124. return this._rollingFrameTime.variance;
  37125. },
  37126. enumerable: true,
  37127. configurable: true
  37128. });
  37129. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  37130. /**
  37131. * Returns the frame time of the most recent frame
  37132. * @return Frame time in milliseconds
  37133. */
  37134. get: function () {
  37135. return this._rollingFrameTime.history(0);
  37136. },
  37137. enumerable: true,
  37138. configurable: true
  37139. });
  37140. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  37141. /**
  37142. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  37143. * @return Framerate in frames per second
  37144. */
  37145. get: function () {
  37146. return 1000.0 / this._rollingFrameTime.average;
  37147. },
  37148. enumerable: true,
  37149. configurable: true
  37150. });
  37151. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  37152. /**
  37153. * Returns the average framerate in frames per second using the most recent frame time
  37154. * @return Framerate in frames per second
  37155. */
  37156. get: function () {
  37157. var history = this._rollingFrameTime.history(0);
  37158. if (history === 0) {
  37159. return 0;
  37160. }
  37161. return 1000.0 / history;
  37162. },
  37163. enumerable: true,
  37164. configurable: true
  37165. });
  37166. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  37167. /**
  37168. * Returns true if enough samples have been taken to completely fill the sliding window
  37169. * @return true if saturated
  37170. */
  37171. get: function () {
  37172. return this._rollingFrameTime.isSaturated();
  37173. },
  37174. enumerable: true,
  37175. configurable: true
  37176. });
  37177. /**
  37178. * Enables contributions to the sliding window sample set
  37179. */
  37180. PerformanceMonitor.prototype.enable = function () {
  37181. this._enabled = true;
  37182. };
  37183. /**
  37184. * Disables contributions to the sliding window sample set
  37185. * Samples will not be interpolated over the disabled period
  37186. */
  37187. PerformanceMonitor.prototype.disable = function () {
  37188. this._enabled = false;
  37189. //clear last sample to avoid interpolating over the disabled period when next enabled
  37190. this._lastFrameTimeMs = null;
  37191. };
  37192. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  37193. /**
  37194. * Returns true if sampling is enabled
  37195. * @return true if enabled
  37196. */
  37197. get: function () {
  37198. return this._enabled;
  37199. },
  37200. enumerable: true,
  37201. configurable: true
  37202. });
  37203. /**
  37204. * Resets performance monitor
  37205. */
  37206. PerformanceMonitor.prototype.reset = function () {
  37207. //clear last sample to avoid interpolating over the disabled period when next enabled
  37208. this._lastFrameTimeMs = null;
  37209. //wipe record
  37210. this._rollingFrameTime.reset();
  37211. };
  37212. return PerformanceMonitor;
  37213. }());
  37214. BABYLON.PerformanceMonitor = PerformanceMonitor;
  37215. /**
  37216. * RollingAverage
  37217. *
  37218. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  37219. */
  37220. var RollingAverage = /** @class */ (function () {
  37221. /**
  37222. * constructor
  37223. * @param length The number of samples required to saturate the sliding window
  37224. */
  37225. function RollingAverage(length) {
  37226. this._samples = new Array(length);
  37227. this.reset();
  37228. }
  37229. /**
  37230. * Adds a sample to the sample set
  37231. * @param v The sample value
  37232. */
  37233. RollingAverage.prototype.add = function (v) {
  37234. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  37235. var delta;
  37236. //we need to check if we've already wrapped round
  37237. if (this.isSaturated()) {
  37238. //remove bottom of stack from mean
  37239. var bottomValue = this._samples[this._pos];
  37240. delta = bottomValue - this.average;
  37241. this.average -= delta / (this._sampleCount - 1);
  37242. this._m2 -= delta * (bottomValue - this.average);
  37243. }
  37244. else {
  37245. this._sampleCount++;
  37246. }
  37247. //add new value to mean
  37248. delta = v - this.average;
  37249. this.average += delta / (this._sampleCount);
  37250. this._m2 += delta * (v - this.average);
  37251. //set the new variance
  37252. this.variance = this._m2 / (this._sampleCount - 1);
  37253. this._samples[this._pos] = v;
  37254. this._pos++;
  37255. this._pos %= this._samples.length; //positive wrap around
  37256. };
  37257. /**
  37258. * Returns previously added values or null if outside of history or outside the sliding window domain
  37259. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  37260. * @return Value previously recorded with add() or null if outside of range
  37261. */
  37262. RollingAverage.prototype.history = function (i) {
  37263. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  37264. return 0;
  37265. }
  37266. var i0 = this._wrapPosition(this._pos - 1.0);
  37267. return this._samples[this._wrapPosition(i0 - i)];
  37268. };
  37269. /**
  37270. * Returns true if enough samples have been taken to completely fill the sliding window
  37271. * @return true if sample-set saturated
  37272. */
  37273. RollingAverage.prototype.isSaturated = function () {
  37274. return this._sampleCount >= this._samples.length;
  37275. };
  37276. /**
  37277. * Resets the rolling average (equivalent to 0 samples taken so far)
  37278. */
  37279. RollingAverage.prototype.reset = function () {
  37280. this.average = 0;
  37281. this.variance = 0;
  37282. this._sampleCount = 0;
  37283. this._pos = 0;
  37284. this._m2 = 0;
  37285. };
  37286. /**
  37287. * Wraps a value around the sample range boundaries
  37288. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  37289. * @return Wrapped position in sample range
  37290. */
  37291. RollingAverage.prototype._wrapPosition = function (i) {
  37292. var max = this._samples.length;
  37293. return ((i % max) + max) % max;
  37294. };
  37295. return RollingAverage;
  37296. }());
  37297. BABYLON.RollingAverage = RollingAverage;
  37298. })(BABYLON || (BABYLON = {}));
  37299. //# sourceMappingURL=babylon.performanceMonitor.js.map
  37300. var BABYLON;
  37301. (function (BABYLON) {
  37302. /**
  37303. * This groups together the common properties used for image processing either in direct forward pass
  37304. * or through post processing effect depending on the use of the image processing pipeline in your scene
  37305. * or not.
  37306. */
  37307. var ImageProcessingConfiguration = /** @class */ (function () {
  37308. function ImageProcessingConfiguration() {
  37309. /**
  37310. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  37311. */
  37312. this.colorCurves = new BABYLON.ColorCurves();
  37313. this._colorCurvesEnabled = false;
  37314. this._colorGradingEnabled = false;
  37315. this._colorGradingWithGreenDepth = true;
  37316. this._colorGradingBGR = true;
  37317. this._exposure = 1.0;
  37318. this._toneMappingEnabled = false;
  37319. this._contrast = 1.0;
  37320. /**
  37321. * Vignette stretch size.
  37322. */
  37323. this.vignetteStretch = 0;
  37324. /**
  37325. * Vignette centre X Offset.
  37326. */
  37327. this.vignetteCentreX = 0;
  37328. /**
  37329. * Vignette centre Y Offset.
  37330. */
  37331. this.vignetteCentreY = 0;
  37332. /**
  37333. * Vignette weight or intensity of the vignette effect.
  37334. */
  37335. this.vignetteWeight = 1.5;
  37336. /**
  37337. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  37338. * if vignetteEnabled is set to true.
  37339. */
  37340. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  37341. /**
  37342. * Camera field of view used by the Vignette effect.
  37343. */
  37344. this.vignetteCameraFov = 0.5;
  37345. this._grainEnabled = false;
  37346. this._grainIntensity = 30;
  37347. this._grainAnimated = false;
  37348. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  37349. this._vignetteEnabled = false;
  37350. this._applyByPostProcess = false;
  37351. this._isEnabled = true;
  37352. /**
  37353. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  37354. * @type {BABYLON.Observable}
  37355. */
  37356. this.onUpdateParameters = new BABYLON.Observable();
  37357. }
  37358. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  37359. /**
  37360. * Gets wether the color curves effect is enabled.
  37361. */
  37362. get: function () {
  37363. return this._colorCurvesEnabled;
  37364. },
  37365. /**
  37366. * Sets wether the color curves effect is enabled.
  37367. */
  37368. set: function (value) {
  37369. if (this._colorCurvesEnabled === value) {
  37370. return;
  37371. }
  37372. this._colorCurvesEnabled = value;
  37373. this._updateParameters();
  37374. },
  37375. enumerable: true,
  37376. configurable: true
  37377. });
  37378. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  37379. /**
  37380. * Gets wether the color grading effect is enabled.
  37381. */
  37382. get: function () {
  37383. return this._colorGradingEnabled;
  37384. },
  37385. /**
  37386. * Sets wether the color grading effect is enabled.
  37387. */
  37388. set: function (value) {
  37389. if (this._colorGradingEnabled === value) {
  37390. return;
  37391. }
  37392. this._colorGradingEnabled = value;
  37393. this._updateParameters();
  37394. },
  37395. enumerable: true,
  37396. configurable: true
  37397. });
  37398. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  37399. /**
  37400. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  37401. */
  37402. get: function () {
  37403. return this._colorGradingWithGreenDepth;
  37404. },
  37405. /**
  37406. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  37407. */
  37408. set: function (value) {
  37409. if (this._colorGradingWithGreenDepth === value) {
  37410. return;
  37411. }
  37412. this._colorGradingWithGreenDepth = value;
  37413. this._updateParameters();
  37414. },
  37415. enumerable: true,
  37416. configurable: true
  37417. });
  37418. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  37419. /**
  37420. * Gets wether the color grading texture contains BGR values.
  37421. */
  37422. get: function () {
  37423. return this._colorGradingBGR;
  37424. },
  37425. /**
  37426. * Sets wether the color grading texture contains BGR values.
  37427. */
  37428. set: function (value) {
  37429. if (this._colorGradingBGR === value) {
  37430. return;
  37431. }
  37432. this._colorGradingBGR = value;
  37433. this._updateParameters();
  37434. },
  37435. enumerable: true,
  37436. configurable: true
  37437. });
  37438. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  37439. /**
  37440. * Gets the Exposure used in the effect.
  37441. */
  37442. get: function () {
  37443. return this._exposure;
  37444. },
  37445. /**
  37446. * Sets the Exposure used in the effect.
  37447. */
  37448. set: function (value) {
  37449. if (this._exposure === value) {
  37450. return;
  37451. }
  37452. this._exposure = value;
  37453. this._updateParameters();
  37454. },
  37455. enumerable: true,
  37456. configurable: true
  37457. });
  37458. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  37459. /**
  37460. * Gets wether the tone mapping effect is enabled.
  37461. */
  37462. get: function () {
  37463. return this._toneMappingEnabled;
  37464. },
  37465. /**
  37466. * Sets wether the tone mapping effect is enabled.
  37467. */
  37468. set: function (value) {
  37469. if (this._toneMappingEnabled === value) {
  37470. return;
  37471. }
  37472. this._toneMappingEnabled = value;
  37473. this._updateParameters();
  37474. },
  37475. enumerable: true,
  37476. configurable: true
  37477. });
  37478. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  37479. /**
  37480. * Gets the contrast used in the effect.
  37481. */
  37482. get: function () {
  37483. return this._contrast;
  37484. },
  37485. /**
  37486. * Sets the contrast used in the effect.
  37487. */
  37488. set: function (value) {
  37489. if (this._contrast === value) {
  37490. return;
  37491. }
  37492. this._contrast = value;
  37493. this._updateParameters();
  37494. },
  37495. enumerable: true,
  37496. configurable: true
  37497. });
  37498. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainEnabled", {
  37499. /**
  37500. * If the grain effect should be enabled.
  37501. */
  37502. get: function () {
  37503. return this._grainEnabled;
  37504. },
  37505. set: function (value) {
  37506. if (this._grainEnabled === value) {
  37507. return;
  37508. }
  37509. this._grainEnabled = value;
  37510. this._updateParameters();
  37511. },
  37512. enumerable: true,
  37513. configurable: true
  37514. });
  37515. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainIntensity", {
  37516. /**
  37517. * Amount of grain to be applied by the grain effect.
  37518. */
  37519. get: function () {
  37520. return this._grainIntensity;
  37521. },
  37522. set: function (value) {
  37523. if (this._grainIntensity === value) {
  37524. return;
  37525. }
  37526. this._grainIntensity = value;
  37527. },
  37528. enumerable: true,
  37529. configurable: true
  37530. });
  37531. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainAnimated", {
  37532. /**
  37533. * If the grain effect should be animated.
  37534. */
  37535. get: function () {
  37536. return this._grainAnimated;
  37537. },
  37538. set: function (value) {
  37539. if (this._grainAnimated === value) {
  37540. return;
  37541. }
  37542. this._grainAnimated = value;
  37543. this._updateParameters();
  37544. },
  37545. enumerable: true,
  37546. configurable: true
  37547. });
  37548. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37549. /**
  37550. * Gets the vignette blend mode allowing different kind of effect.
  37551. */
  37552. get: function () {
  37553. return this._vignetteBlendMode;
  37554. },
  37555. /**
  37556. * Sets the vignette blend mode allowing different kind of effect.
  37557. */
  37558. set: function (value) {
  37559. if (this._vignetteBlendMode === value) {
  37560. return;
  37561. }
  37562. this._vignetteBlendMode = value;
  37563. this._updateParameters();
  37564. },
  37565. enumerable: true,
  37566. configurable: true
  37567. });
  37568. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37569. /**
  37570. * Gets wether the vignette effect is enabled.
  37571. */
  37572. get: function () {
  37573. return this._vignetteEnabled;
  37574. },
  37575. /**
  37576. * Sets wether the vignette effect is enabled.
  37577. */
  37578. set: function (value) {
  37579. if (this._vignetteEnabled === value) {
  37580. return;
  37581. }
  37582. this._vignetteEnabled = value;
  37583. this._updateParameters();
  37584. },
  37585. enumerable: true,
  37586. configurable: true
  37587. });
  37588. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37589. /**
  37590. * Gets wether the image processing is applied through a post process or not.
  37591. */
  37592. get: function () {
  37593. return this._applyByPostProcess;
  37594. },
  37595. /**
  37596. * Sets wether the image processing is applied through a post process or not.
  37597. */
  37598. set: function (value) {
  37599. if (this._applyByPostProcess === value) {
  37600. return;
  37601. }
  37602. this._applyByPostProcess = value;
  37603. this._updateParameters();
  37604. },
  37605. enumerable: true,
  37606. configurable: true
  37607. });
  37608. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37609. /**
  37610. * Gets wether the image processing is enabled or not.
  37611. */
  37612. get: function () {
  37613. return this._isEnabled;
  37614. },
  37615. /**
  37616. * Sets wether the image processing is enabled or not.
  37617. */
  37618. set: function (value) {
  37619. if (this._isEnabled === value) {
  37620. return;
  37621. }
  37622. this._isEnabled = value;
  37623. this._updateParameters();
  37624. },
  37625. enumerable: true,
  37626. configurable: true
  37627. });
  37628. /**
  37629. * Method called each time the image processing information changes requires to recompile the effect.
  37630. */
  37631. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37632. this.onUpdateParameters.notifyObservers(this);
  37633. };
  37634. ImageProcessingConfiguration.prototype.getClassName = function () {
  37635. return "ImageProcessingConfiguration";
  37636. };
  37637. /**
  37638. * Prepare the list of uniforms associated with the Image Processing effects.
  37639. * @param uniformsList The list of uniforms used in the effect
  37640. * @param defines the list of defines currently in use
  37641. */
  37642. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37643. if (defines.EXPOSURE) {
  37644. uniforms.push("exposureLinear");
  37645. }
  37646. if (defines.CONTRAST) {
  37647. uniforms.push("contrast");
  37648. }
  37649. if (defines.COLORGRADING) {
  37650. uniforms.push("colorTransformSettings");
  37651. }
  37652. if (defines.VIGNETTE) {
  37653. uniforms.push("vInverseScreenSize");
  37654. uniforms.push("vignetteSettings1");
  37655. uniforms.push("vignetteSettings2");
  37656. }
  37657. if (defines.COLORCURVES) {
  37658. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37659. }
  37660. if (defines.GRAIN) {
  37661. uniforms.push("grainVarianceAmount");
  37662. uniforms.push("grainAnimatedSeed");
  37663. }
  37664. };
  37665. /**
  37666. * Prepare the list of samplers associated with the Image Processing effects.
  37667. * @param uniformsList The list of uniforms used in the effect
  37668. * @param defines the list of defines currently in use
  37669. */
  37670. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37671. if (defines.COLORGRADING) {
  37672. samplersList.push("txColorTransform");
  37673. }
  37674. };
  37675. /**
  37676. * Prepare the list of defines associated to the shader.
  37677. * @param defines the list of defines to complete
  37678. */
  37679. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37680. if (forPostProcess === void 0) { forPostProcess = false; }
  37681. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37682. defines.VIGNETTE = false;
  37683. defines.TONEMAPPING = false;
  37684. defines.CONTRAST = false;
  37685. defines.EXPOSURE = false;
  37686. defines.COLORCURVES = false;
  37687. defines.COLORGRADING = false;
  37688. defines.COLORGRADING3D = false;
  37689. defines.IMAGEPROCESSING = false;
  37690. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37691. return;
  37692. }
  37693. defines.VIGNETTE = this.vignetteEnabled;
  37694. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37695. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37696. defines.TONEMAPPING = this.toneMappingEnabled;
  37697. defines.CONTRAST = (this.contrast !== 1.0);
  37698. defines.EXPOSURE = (this.exposure !== 1.0);
  37699. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37700. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37701. if (defines.COLORGRADING) {
  37702. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37703. }
  37704. else {
  37705. defines.COLORGRADING3D = false;
  37706. }
  37707. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37708. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37709. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37710. defines.GRAIN = this.grainEnabled;
  37711. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING || defines.GRAIN;
  37712. };
  37713. /**
  37714. * Returns true if all the image processing information are ready.
  37715. */
  37716. ImageProcessingConfiguration.prototype.isReady = function () {
  37717. // Color Grading texure can not be none blocking.
  37718. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37719. };
  37720. /**
  37721. * Binds the image processing to the shader.
  37722. * @param effect The effect to bind to
  37723. */
  37724. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37725. if (aspectRatio === void 0) { aspectRatio = 1; }
  37726. // Color Curves
  37727. if (this._colorCurvesEnabled && this.colorCurves) {
  37728. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37729. }
  37730. // Vignette
  37731. if (this._vignetteEnabled) {
  37732. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37733. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37734. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37735. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37736. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37737. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37738. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37739. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37740. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37741. var vignettePower = -2.0 * this.vignetteWeight;
  37742. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37743. }
  37744. // Exposure
  37745. effect.setFloat("exposureLinear", this.exposure);
  37746. // Contrast
  37747. effect.setFloat("contrast", this.contrast);
  37748. // Color transform settings
  37749. if (this.colorGradingTexture) {
  37750. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37751. var textureSize = this.colorGradingTexture.getSize().height;
  37752. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37753. 0.5 / textureSize, // textureOffset
  37754. textureSize, // textureSize
  37755. this.colorGradingTexture.level // weight
  37756. );
  37757. }
  37758. effect.setFloat("grainVarianceAmount", this.grainIntensity);
  37759. effect.setFloat("grainAnimatedSeed", this.grainAnimated ? Math.random() + 1 : 1);
  37760. };
  37761. /**
  37762. * Clones the current image processing instance.
  37763. * @return The cloned image processing
  37764. */
  37765. ImageProcessingConfiguration.prototype.clone = function () {
  37766. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37767. };
  37768. /**
  37769. * Serializes the current image processing instance to a json representation.
  37770. * @return a JSON representation
  37771. */
  37772. ImageProcessingConfiguration.prototype.serialize = function () {
  37773. return BABYLON.SerializationHelper.Serialize(this);
  37774. };
  37775. /**
  37776. * Parses the image processing from a json representation.
  37777. * @param source the JSON source to parse
  37778. * @return The parsed image processing
  37779. */
  37780. ImageProcessingConfiguration.Parse = function (source) {
  37781. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37782. };
  37783. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  37784. /**
  37785. * Used to apply the vignette as a mix with the pixel color.
  37786. */
  37787. get: function () {
  37788. return this._VIGNETTEMODE_MULTIPLY;
  37789. },
  37790. enumerable: true,
  37791. configurable: true
  37792. });
  37793. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  37794. /**
  37795. * Used to apply the vignette as a replacement of the pixel color.
  37796. */
  37797. get: function () {
  37798. return this._VIGNETTEMODE_OPAQUE;
  37799. },
  37800. enumerable: true,
  37801. configurable: true
  37802. });
  37803. // Static constants associated to the image processing.
  37804. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  37805. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  37806. __decorate([
  37807. BABYLON.serializeAsColorCurves()
  37808. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  37809. __decorate([
  37810. BABYLON.serialize()
  37811. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  37812. __decorate([
  37813. BABYLON.serializeAsTexture()
  37814. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  37815. __decorate([
  37816. BABYLON.serialize()
  37817. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  37818. __decorate([
  37819. BABYLON.serialize()
  37820. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  37821. __decorate([
  37822. BABYLON.serialize()
  37823. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  37824. __decorate([
  37825. BABYLON.serialize()
  37826. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  37827. __decorate([
  37828. BABYLON.serialize()
  37829. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  37830. __decorate([
  37831. BABYLON.serialize()
  37832. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  37833. __decorate([
  37834. BABYLON.serialize()
  37835. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  37836. __decorate([
  37837. BABYLON.serialize()
  37838. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  37839. __decorate([
  37840. BABYLON.serialize()
  37841. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  37842. __decorate([
  37843. BABYLON.serialize()
  37844. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  37845. __decorate([
  37846. BABYLON.serializeAsColor4()
  37847. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  37848. __decorate([
  37849. BABYLON.serialize()
  37850. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  37851. __decorate([
  37852. BABYLON.serialize()
  37853. ], ImageProcessingConfiguration.prototype, "_grainEnabled", void 0);
  37854. __decorate([
  37855. BABYLON.serialize()
  37856. ], ImageProcessingConfiguration.prototype, "_grainIntensity", void 0);
  37857. __decorate([
  37858. BABYLON.serialize()
  37859. ], ImageProcessingConfiguration.prototype, "_grainAnimated", void 0);
  37860. __decorate([
  37861. BABYLON.serialize()
  37862. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  37863. __decorate([
  37864. BABYLON.serialize()
  37865. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  37866. __decorate([
  37867. BABYLON.serialize()
  37868. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  37869. __decorate([
  37870. BABYLON.serialize()
  37871. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  37872. return ImageProcessingConfiguration;
  37873. }());
  37874. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  37875. })(BABYLON || (BABYLON = {}));
  37876. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  37877. var BABYLON;
  37878. (function (BABYLON) {
  37879. /**
  37880. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  37881. * It can help converting any input color in a desired output one. This can then be used to create effects
  37882. * from sepia, black and white to sixties or futuristic rendering...
  37883. *
  37884. * The only supported format is currently 3dl.
  37885. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  37886. */
  37887. var ColorGradingTexture = /** @class */ (function (_super) {
  37888. __extends(ColorGradingTexture, _super);
  37889. /**
  37890. * Instantiates a ColorGradingTexture from the following parameters.
  37891. *
  37892. * @param url The location of the color gradind data (currently only supporting 3dl)
  37893. * @param scene The scene the texture will be used in
  37894. */
  37895. function ColorGradingTexture(url, scene) {
  37896. var _this = _super.call(this, scene) || this;
  37897. if (!url) {
  37898. return _this;
  37899. }
  37900. _this._engine = scene.getEngine();
  37901. _this._textureMatrix = BABYLON.Matrix.Identity();
  37902. _this.name = url;
  37903. _this.url = url;
  37904. _this.hasAlpha = false;
  37905. _this.isCube = false;
  37906. _this.is3D = _this._engine.webGLVersion > 1;
  37907. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37908. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37909. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37910. _this.anisotropicFilteringLevel = 1;
  37911. _this._texture = _this._getFromCache(url, true);
  37912. if (!_this._texture) {
  37913. if (!scene.useDelayedTextureLoading) {
  37914. _this.loadTexture();
  37915. }
  37916. else {
  37917. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  37918. }
  37919. }
  37920. return _this;
  37921. }
  37922. /**
  37923. * Returns the texture matrix used in most of the material.
  37924. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  37925. */
  37926. ColorGradingTexture.prototype.getTextureMatrix = function () {
  37927. return this._textureMatrix;
  37928. };
  37929. /**
  37930. * Occurs when the file being loaded is a .3dl LUT file.
  37931. */
  37932. ColorGradingTexture.prototype.load3dlTexture = function () {
  37933. var engine = this._engine;
  37934. var texture;
  37935. if (engine.webGLVersion === 1) {
  37936. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37937. }
  37938. else {
  37939. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37940. }
  37941. this._texture = texture;
  37942. var callback = function (text) {
  37943. if (typeof text !== "string") {
  37944. return;
  37945. }
  37946. var data = null;
  37947. var tempData = null;
  37948. var line;
  37949. var lines = text.split('\n');
  37950. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  37951. var maxColor = 0;
  37952. for (var i = 0; i < lines.length; i++) {
  37953. line = lines[i];
  37954. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  37955. continue;
  37956. if (line.indexOf('#') === 0)
  37957. continue;
  37958. var words = line.split(" ");
  37959. if (size === 0) {
  37960. // Number of space + one
  37961. size = words.length;
  37962. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  37963. tempData = new Float32Array(size * size * size * 4);
  37964. continue;
  37965. }
  37966. if (size != 0) {
  37967. var r = Math.max(parseInt(words[0]), 0);
  37968. var g = Math.max(parseInt(words[1]), 0);
  37969. var b = Math.max(parseInt(words[2]), 0);
  37970. maxColor = Math.max(r, maxColor);
  37971. maxColor = Math.max(g, maxColor);
  37972. maxColor = Math.max(b, maxColor);
  37973. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  37974. if (tempData) {
  37975. tempData[pixelStorageIndex + 0] = r;
  37976. tempData[pixelStorageIndex + 1] = g;
  37977. tempData[pixelStorageIndex + 2] = b;
  37978. }
  37979. pixelIndexSlice++;
  37980. if (pixelIndexSlice % size == 0) {
  37981. pixelIndexH++;
  37982. pixelIndexSlice = 0;
  37983. if (pixelIndexH % size == 0) {
  37984. pixelIndexW++;
  37985. pixelIndexH = 0;
  37986. }
  37987. }
  37988. }
  37989. }
  37990. if (tempData && data) {
  37991. for (var i = 0; i < tempData.length; i++) {
  37992. if (i > 0 && (i + 1) % 4 === 0) {
  37993. data[i] = 255;
  37994. }
  37995. else {
  37996. var value = tempData[i];
  37997. data[i] = (value / maxColor * 255);
  37998. }
  37999. }
  38000. }
  38001. if (texture.is3D) {
  38002. texture.updateSize(size, size, size);
  38003. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38004. }
  38005. else {
  38006. texture.updateSize(size * size, size);
  38007. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38008. }
  38009. };
  38010. var scene = this.getScene();
  38011. if (scene) {
  38012. scene._loadFile(this.url, callback);
  38013. }
  38014. else {
  38015. this._engine._loadFile(this.url, callback);
  38016. }
  38017. return this._texture;
  38018. };
  38019. /**
  38020. * Starts the loading process of the texture.
  38021. */
  38022. ColorGradingTexture.prototype.loadTexture = function () {
  38023. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  38024. this.load3dlTexture();
  38025. }
  38026. };
  38027. /**
  38028. * Clones the color gradind texture.
  38029. */
  38030. ColorGradingTexture.prototype.clone = function () {
  38031. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  38032. // Base texture
  38033. newTexture.level = this.level;
  38034. return newTexture;
  38035. };
  38036. /**
  38037. * Called during delayed load for textures.
  38038. */
  38039. ColorGradingTexture.prototype.delayLoad = function () {
  38040. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  38041. return;
  38042. }
  38043. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38044. this._texture = this._getFromCache(this.url, true);
  38045. if (!this._texture) {
  38046. this.loadTexture();
  38047. }
  38048. };
  38049. /**
  38050. * Parses a color grading texture serialized by Babylon.
  38051. * @param parsedTexture The texture information being parsedTexture
  38052. * @param scene The scene to load the texture in
  38053. * @param rootUrl The root url of the data assets to load
  38054. * @return A color gradind texture
  38055. */
  38056. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  38057. var texture = null;
  38058. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  38059. texture = new ColorGradingTexture(parsedTexture.name, scene);
  38060. texture.name = parsedTexture.name;
  38061. texture.level = parsedTexture.level;
  38062. }
  38063. return texture;
  38064. };
  38065. /**
  38066. * Serializes the LUT texture to json format.
  38067. */
  38068. ColorGradingTexture.prototype.serialize = function () {
  38069. if (!this.name) {
  38070. return null;
  38071. }
  38072. var serializationObject = {};
  38073. serializationObject.name = this.name;
  38074. serializationObject.level = this.level;
  38075. serializationObject.customType = "BABYLON.ColorGradingTexture";
  38076. return serializationObject;
  38077. };
  38078. /**
  38079. * Empty line regex stored for GC.
  38080. */
  38081. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  38082. return ColorGradingTexture;
  38083. }(BABYLON.BaseTexture));
  38084. BABYLON.ColorGradingTexture = ColorGradingTexture;
  38085. })(BABYLON || (BABYLON = {}));
  38086. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  38087. var BABYLON;
  38088. (function (BABYLON) {
  38089. /**
  38090. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38091. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38092. * 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;
  38093. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38094. */
  38095. var ColorCurves = /** @class */ (function () {
  38096. function ColorCurves() {
  38097. this._dirty = true;
  38098. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  38099. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  38100. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38101. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  38102. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38103. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  38104. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  38105. this._globalHue = 30;
  38106. this._globalDensity = 0;
  38107. this._globalSaturation = 0;
  38108. this._globalExposure = 0;
  38109. this._highlightsHue = 30;
  38110. this._highlightsDensity = 0;
  38111. this._highlightsSaturation = 0;
  38112. this._highlightsExposure = 0;
  38113. this._midtonesHue = 30;
  38114. this._midtonesDensity = 0;
  38115. this._midtonesSaturation = 0;
  38116. this._midtonesExposure = 0;
  38117. this._shadowsHue = 30;
  38118. this._shadowsDensity = 0;
  38119. this._shadowsSaturation = 0;
  38120. this._shadowsExposure = 0;
  38121. }
  38122. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  38123. /**
  38124. * Gets the global Hue value.
  38125. * 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).
  38126. */
  38127. get: function () {
  38128. return this._globalHue;
  38129. },
  38130. /**
  38131. * Sets the global Hue value.
  38132. * 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).
  38133. */
  38134. set: function (value) {
  38135. this._globalHue = value;
  38136. this._dirty = true;
  38137. },
  38138. enumerable: true,
  38139. configurable: true
  38140. });
  38141. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  38142. /**
  38143. * Gets the global Density value.
  38144. * 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.
  38145. * Values less than zero provide a filter of opposite hue.
  38146. */
  38147. get: function () {
  38148. return this._globalDensity;
  38149. },
  38150. /**
  38151. * Sets the global Density value.
  38152. * 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.
  38153. * Values less than zero provide a filter of opposite hue.
  38154. */
  38155. set: function (value) {
  38156. this._globalDensity = value;
  38157. this._dirty = true;
  38158. },
  38159. enumerable: true,
  38160. configurable: true
  38161. });
  38162. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  38163. /**
  38164. * Gets the global Saturation value.
  38165. * 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.
  38166. */
  38167. get: function () {
  38168. return this._globalSaturation;
  38169. },
  38170. /**
  38171. * Sets the global Saturation value.
  38172. * 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.
  38173. */
  38174. set: function (value) {
  38175. this._globalSaturation = value;
  38176. this._dirty = true;
  38177. },
  38178. enumerable: true,
  38179. configurable: true
  38180. });
  38181. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  38182. /**
  38183. * Gets the highlights Hue value.
  38184. * 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).
  38185. */
  38186. get: function () {
  38187. return this._highlightsHue;
  38188. },
  38189. /**
  38190. * Sets the highlights Hue value.
  38191. * 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).
  38192. */
  38193. set: function (value) {
  38194. this._highlightsHue = value;
  38195. this._dirty = true;
  38196. },
  38197. enumerable: true,
  38198. configurable: true
  38199. });
  38200. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  38201. /**
  38202. * Gets the highlights Density value.
  38203. * 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.
  38204. * Values less than zero provide a filter of opposite hue.
  38205. */
  38206. get: function () {
  38207. return this._highlightsDensity;
  38208. },
  38209. /**
  38210. * Sets the highlights Density value.
  38211. * 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.
  38212. * Values less than zero provide a filter of opposite hue.
  38213. */
  38214. set: function (value) {
  38215. this._highlightsDensity = value;
  38216. this._dirty = true;
  38217. },
  38218. enumerable: true,
  38219. configurable: true
  38220. });
  38221. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  38222. /**
  38223. * Gets the highlights Saturation value.
  38224. * 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.
  38225. */
  38226. get: function () {
  38227. return this._highlightsSaturation;
  38228. },
  38229. /**
  38230. * Sets the highlights Saturation value.
  38231. * 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.
  38232. */
  38233. set: function (value) {
  38234. this._highlightsSaturation = value;
  38235. this._dirty = true;
  38236. },
  38237. enumerable: true,
  38238. configurable: true
  38239. });
  38240. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  38241. /**
  38242. * Gets the highlights Exposure value.
  38243. * 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.
  38244. */
  38245. get: function () {
  38246. return this._highlightsExposure;
  38247. },
  38248. /**
  38249. * Sets the highlights Exposure value.
  38250. * 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.
  38251. */
  38252. set: function (value) {
  38253. this._highlightsExposure = value;
  38254. this._dirty = true;
  38255. },
  38256. enumerable: true,
  38257. configurable: true
  38258. });
  38259. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  38260. /**
  38261. * Gets the midtones Hue value.
  38262. * 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).
  38263. */
  38264. get: function () {
  38265. return this._midtonesHue;
  38266. },
  38267. /**
  38268. * Sets the midtones Hue value.
  38269. * 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).
  38270. */
  38271. set: function (value) {
  38272. this._midtonesHue = value;
  38273. this._dirty = true;
  38274. },
  38275. enumerable: true,
  38276. configurable: true
  38277. });
  38278. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  38279. /**
  38280. * Gets the midtones Density value.
  38281. * 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.
  38282. * Values less than zero provide a filter of opposite hue.
  38283. */
  38284. get: function () {
  38285. return this._midtonesDensity;
  38286. },
  38287. /**
  38288. * Sets the midtones Density value.
  38289. * 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.
  38290. * Values less than zero provide a filter of opposite hue.
  38291. */
  38292. set: function (value) {
  38293. this._midtonesDensity = value;
  38294. this._dirty = true;
  38295. },
  38296. enumerable: true,
  38297. configurable: true
  38298. });
  38299. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  38300. /**
  38301. * Gets the midtones Saturation value.
  38302. * 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.
  38303. */
  38304. get: function () {
  38305. return this._midtonesSaturation;
  38306. },
  38307. /**
  38308. * Sets the midtones Saturation value.
  38309. * 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.
  38310. */
  38311. set: function (value) {
  38312. this._midtonesSaturation = value;
  38313. this._dirty = true;
  38314. },
  38315. enumerable: true,
  38316. configurable: true
  38317. });
  38318. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  38319. /**
  38320. * Gets the midtones Exposure value.
  38321. * 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.
  38322. */
  38323. get: function () {
  38324. return this._midtonesExposure;
  38325. },
  38326. /**
  38327. * Sets the midtones Exposure value.
  38328. * 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.
  38329. */
  38330. set: function (value) {
  38331. this._midtonesExposure = value;
  38332. this._dirty = true;
  38333. },
  38334. enumerable: true,
  38335. configurable: true
  38336. });
  38337. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  38338. /**
  38339. * Gets the shadows Hue value.
  38340. * 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).
  38341. */
  38342. get: function () {
  38343. return this._shadowsHue;
  38344. },
  38345. /**
  38346. * Sets the shadows Hue value.
  38347. * 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).
  38348. */
  38349. set: function (value) {
  38350. this._shadowsHue = value;
  38351. this._dirty = true;
  38352. },
  38353. enumerable: true,
  38354. configurable: true
  38355. });
  38356. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  38357. /**
  38358. * Gets the shadows Density value.
  38359. * 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.
  38360. * Values less than zero provide a filter of opposite hue.
  38361. */
  38362. get: function () {
  38363. return this._shadowsDensity;
  38364. },
  38365. /**
  38366. * Sets the shadows Density value.
  38367. * 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.
  38368. * Values less than zero provide a filter of opposite hue.
  38369. */
  38370. set: function (value) {
  38371. this._shadowsDensity = value;
  38372. this._dirty = true;
  38373. },
  38374. enumerable: true,
  38375. configurable: true
  38376. });
  38377. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  38378. /**
  38379. * Gets the shadows Saturation value.
  38380. * 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.
  38381. */
  38382. get: function () {
  38383. return this._shadowsSaturation;
  38384. },
  38385. /**
  38386. * Sets the shadows Saturation value.
  38387. * 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.
  38388. */
  38389. set: function (value) {
  38390. this._shadowsSaturation = value;
  38391. this._dirty = true;
  38392. },
  38393. enumerable: true,
  38394. configurable: true
  38395. });
  38396. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  38397. /**
  38398. * Gets the shadows Exposure value.
  38399. * 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.
  38400. */
  38401. get: function () {
  38402. return this._shadowsExposure;
  38403. },
  38404. /**
  38405. * Sets the shadows Exposure value.
  38406. * 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.
  38407. */
  38408. set: function (value) {
  38409. this._shadowsExposure = value;
  38410. this._dirty = true;
  38411. },
  38412. enumerable: true,
  38413. configurable: true
  38414. });
  38415. ColorCurves.prototype.getClassName = function () {
  38416. return "ColorCurves";
  38417. };
  38418. /**
  38419. * Binds the color curves to the shader.
  38420. * @param colorCurves The color curve to bind
  38421. * @param effect The effect to bind to
  38422. */
  38423. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  38424. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  38425. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  38426. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  38427. if (colorCurves._dirty) {
  38428. colorCurves._dirty = false;
  38429. // Fill in global info.
  38430. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  38431. // Compute highlights info.
  38432. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  38433. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  38434. // Compute midtones info.
  38435. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  38436. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  38437. // Compute shadows info.
  38438. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  38439. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  38440. // Compute deltas (neutral is midtones).
  38441. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  38442. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  38443. }
  38444. if (effect) {
  38445. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  38446. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  38447. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  38448. }
  38449. };
  38450. /**
  38451. * Prepare the list of uniforms associated with the ColorCurves effects.
  38452. * @param uniformsList The list of uniforms used in the effect
  38453. */
  38454. ColorCurves.PrepareUniforms = function (uniformsList) {
  38455. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  38456. };
  38457. /**
  38458. * Returns color grading data based on a hue, density, saturation and exposure value.
  38459. * @param filterHue The hue of the color filter.
  38460. * @param filterDensity The density of the color filter.
  38461. * @param saturation The saturation.
  38462. * @param exposure The exposure.
  38463. * @param result The result data container.
  38464. */
  38465. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  38466. if (hue == null) {
  38467. return;
  38468. }
  38469. hue = ColorCurves.clamp(hue, 0, 360);
  38470. density = ColorCurves.clamp(density, -100, 100);
  38471. saturation = ColorCurves.clamp(saturation, -100, 100);
  38472. exposure = ColorCurves.clamp(exposure, -100, 100);
  38473. // Remap the slider/config filter density with non-linear mapping and also scale by half
  38474. // so that the maximum filter density is only 50% control. This provides fine control
  38475. // for small values and reasonable range.
  38476. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  38477. density *= 0.5;
  38478. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  38479. if (density < 0) {
  38480. density *= -1;
  38481. hue = (hue + 180) % 360;
  38482. }
  38483. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  38484. result.scaleToRef(2, result);
  38485. result.a = 1 + 0.01 * saturation;
  38486. };
  38487. /**
  38488. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  38489. * @param value The input slider value in range [-100,100].
  38490. * @returns Adjusted value.
  38491. */
  38492. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  38493. value /= 100;
  38494. var x = Math.abs(value);
  38495. x = Math.pow(x, 2);
  38496. if (value < 0) {
  38497. x *= -1;
  38498. }
  38499. x *= 100;
  38500. return x;
  38501. };
  38502. /**
  38503. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  38504. * @param hue The hue (H) input.
  38505. * @param saturation The saturation (S) input.
  38506. * @param brightness The brightness (B) input.
  38507. * @result An RGBA color represented as Vector4.
  38508. */
  38509. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  38510. var h = ColorCurves.clamp(hue, 0, 360);
  38511. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  38512. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  38513. if (s === 0) {
  38514. result.r = v;
  38515. result.g = v;
  38516. result.b = v;
  38517. }
  38518. else {
  38519. // sector 0 to 5
  38520. h /= 60;
  38521. var i = Math.floor(h);
  38522. // fractional part of h
  38523. var f = h - i;
  38524. var p = v * (1 - s);
  38525. var q = v * (1 - s * f);
  38526. var t = v * (1 - s * (1 - f));
  38527. switch (i) {
  38528. case 0:
  38529. result.r = v;
  38530. result.g = t;
  38531. result.b = p;
  38532. break;
  38533. case 1:
  38534. result.r = q;
  38535. result.g = v;
  38536. result.b = p;
  38537. break;
  38538. case 2:
  38539. result.r = p;
  38540. result.g = v;
  38541. result.b = t;
  38542. break;
  38543. case 3:
  38544. result.r = p;
  38545. result.g = q;
  38546. result.b = v;
  38547. break;
  38548. case 4:
  38549. result.r = t;
  38550. result.g = p;
  38551. result.b = v;
  38552. break;
  38553. default:// case 5:
  38554. result.r = v;
  38555. result.g = p;
  38556. result.b = q;
  38557. break;
  38558. }
  38559. }
  38560. result.a = 1;
  38561. };
  38562. /**
  38563. * Returns a value clamped between min and max
  38564. * @param value The value to clamp
  38565. * @param min The minimum of value
  38566. * @param max The maximum of value
  38567. * @returns The clamped value.
  38568. */
  38569. ColorCurves.clamp = function (value, min, max) {
  38570. return Math.min(Math.max(value, min), max);
  38571. };
  38572. /**
  38573. * Clones the current color curve instance.
  38574. * @return The cloned curves
  38575. */
  38576. ColorCurves.prototype.clone = function () {
  38577. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38578. };
  38579. /**
  38580. * Serializes the current color curve instance to a json representation.
  38581. * @return a JSON representation
  38582. */
  38583. ColorCurves.prototype.serialize = function () {
  38584. return BABYLON.SerializationHelper.Serialize(this);
  38585. };
  38586. /**
  38587. * Parses the color curve from a json representation.
  38588. * @param source the JSON source to parse
  38589. * @return The parsed curves
  38590. */
  38591. ColorCurves.Parse = function (source) {
  38592. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38593. };
  38594. __decorate([
  38595. BABYLON.serialize()
  38596. ], ColorCurves.prototype, "_globalHue", void 0);
  38597. __decorate([
  38598. BABYLON.serialize()
  38599. ], ColorCurves.prototype, "_globalDensity", void 0);
  38600. __decorate([
  38601. BABYLON.serialize()
  38602. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38603. __decorate([
  38604. BABYLON.serialize()
  38605. ], ColorCurves.prototype, "_globalExposure", void 0);
  38606. __decorate([
  38607. BABYLON.serialize()
  38608. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38609. __decorate([
  38610. BABYLON.serialize()
  38611. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38612. __decorate([
  38613. BABYLON.serialize()
  38614. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38615. __decorate([
  38616. BABYLON.serialize()
  38617. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38618. __decorate([
  38619. BABYLON.serialize()
  38620. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38621. __decorate([
  38622. BABYLON.serialize()
  38623. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38624. __decorate([
  38625. BABYLON.serialize()
  38626. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38627. __decorate([
  38628. BABYLON.serialize()
  38629. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38630. return ColorCurves;
  38631. }());
  38632. BABYLON.ColorCurves = ColorCurves;
  38633. })(BABYLON || (BABYLON = {}));
  38634. //# sourceMappingURL=babylon.colorCurves.js.map
  38635. //# sourceMappingURL=babylon.behavior.js.map
  38636. var BABYLON;
  38637. (function (BABYLON) {
  38638. /**
  38639. * "Static Class" containing the most commonly used helper while dealing with material for
  38640. * rendering purpose.
  38641. *
  38642. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38643. *
  38644. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38645. */
  38646. var MaterialHelper = /** @class */ (function () {
  38647. function MaterialHelper() {
  38648. }
  38649. /**
  38650. * Bind the current view position to an effect.
  38651. * @param effect The effect to be bound
  38652. * @param scene The scene the eyes position is used from
  38653. */
  38654. MaterialHelper.BindEyePosition = function (effect, scene) {
  38655. if (scene._forcedViewPosition) {
  38656. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38657. return;
  38658. }
  38659. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38660. };
  38661. /**
  38662. * Helps preparing the defines values about the UVs in used in the effect.
  38663. * UVs are shared as much as we can accross chanels in the shaders.
  38664. * @param texture The texture we are preparing the UVs for
  38665. * @param defines The defines to update
  38666. * @param key The chanel key "diffuse", "specular"... used in the shader
  38667. */
  38668. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38669. defines._needUVs = true;
  38670. defines[key] = true;
  38671. if (texture.getTextureMatrix().isIdentity(true)) {
  38672. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38673. if (texture.coordinatesIndex === 0) {
  38674. defines["MAINUV1"] = true;
  38675. }
  38676. else {
  38677. defines["MAINUV2"] = true;
  38678. }
  38679. }
  38680. else {
  38681. defines[key + "DIRECTUV"] = 0;
  38682. }
  38683. };
  38684. /**
  38685. * Binds a texture matrix value to its corrsponding uniform
  38686. * @param texture The texture to bind the matrix for
  38687. * @param uniformBuffer The uniform buffer receivin the data
  38688. * @param key The chanel key "diffuse", "specular"... used in the shader
  38689. */
  38690. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38691. var matrix = texture.getTextureMatrix();
  38692. if (!matrix.isIdentity(true)) {
  38693. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38694. }
  38695. };
  38696. /**
  38697. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38698. * @param mesh defines the current mesh
  38699. * @param scene defines the current scene
  38700. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38701. * @param pointsCloud defines if point cloud rendering has to be turned on
  38702. * @param fogEnabled defines if fog has to be turned on
  38703. * @param alphaTest defines if alpha testing has to be turned on
  38704. * @param defines defines the current list of defines
  38705. */
  38706. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38707. if (defines._areMiscDirty) {
  38708. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38709. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  38710. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38711. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38712. defines["ALPHATEST"] = alphaTest;
  38713. }
  38714. };
  38715. /**
  38716. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38717. * @param scene defines the current scene
  38718. * @param engine defines the current engine
  38719. * @param defines specifies the list of active defines
  38720. * @param useInstances defines if instances have to be turned on
  38721. * @param useClipPlane defines if clip plane have to be turned on
  38722. */
  38723. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38724. if (useClipPlane === void 0) { useClipPlane = null; }
  38725. var changed = false;
  38726. if (useClipPlane == null) {
  38727. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38728. }
  38729. if (defines["CLIPPLANE"] !== useClipPlane) {
  38730. defines["CLIPPLANE"] = useClipPlane;
  38731. changed = true;
  38732. }
  38733. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38734. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38735. changed = true;
  38736. }
  38737. if (defines["INSTANCES"] !== useInstances) {
  38738. defines["INSTANCES"] = useInstances;
  38739. changed = true;
  38740. }
  38741. if (changed) {
  38742. defines.markAsUnprocessed();
  38743. }
  38744. };
  38745. /**
  38746. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38747. * @param mesh The mesh containing the geometry data we will draw
  38748. * @param defines The defines to update
  38749. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38750. * @param useBones Precise whether bones should be used or not (override mesh info)
  38751. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38752. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38753. * @returns false if defines are considered not dirty and have not been checked
  38754. */
  38755. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38756. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38757. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38758. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38759. return false;
  38760. }
  38761. defines._normals = defines._needNormals;
  38762. defines._uvs = defines._needUVs;
  38763. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38764. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38765. defines["TANGENT"] = true;
  38766. }
  38767. if (defines._needUVs) {
  38768. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38769. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38770. }
  38771. else {
  38772. defines["UV1"] = false;
  38773. defines["UV2"] = false;
  38774. }
  38775. if (useVertexColor) {
  38776. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38777. defines["VERTEXCOLOR"] = hasVertexColors;
  38778. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38779. }
  38780. if (useBones) {
  38781. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38782. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  38783. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  38784. }
  38785. else {
  38786. defines["NUM_BONE_INFLUENCERS"] = 0;
  38787. defines["BonesPerMesh"] = 0;
  38788. }
  38789. }
  38790. if (useMorphTargets) {
  38791. var manager = mesh.morphTargetManager;
  38792. if (manager) {
  38793. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  38794. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  38795. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  38796. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  38797. }
  38798. else {
  38799. defines["MORPHTARGETS_TANGENT"] = false;
  38800. defines["MORPHTARGETS_NORMAL"] = false;
  38801. defines["MORPHTARGETS"] = false;
  38802. defines["NUM_MORPH_INFLUENCERS"] = 0;
  38803. }
  38804. }
  38805. return true;
  38806. };
  38807. /**
  38808. * Prepares the defines related to the light information passed in parameter
  38809. * @param scene The scene we are intending to draw
  38810. * @param mesh The mesh the effect is compiling for
  38811. * @param defines The defines to update
  38812. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  38813. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  38814. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  38815. * @returns true if normals will be required for the rest of the effect
  38816. */
  38817. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  38818. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38819. if (disableLighting === void 0) { disableLighting = false; }
  38820. if (!defines._areLightsDirty) {
  38821. return defines._needNormals;
  38822. }
  38823. var lightIndex = 0;
  38824. var needNormals = false;
  38825. var needRebuild = false;
  38826. var lightmapMode = false;
  38827. var shadowEnabled = false;
  38828. var specularEnabled = false;
  38829. if (scene.lightsEnabled && !disableLighting) {
  38830. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  38831. var light = _a[_i];
  38832. needNormals = true;
  38833. if (defines["LIGHT" + lightIndex] === undefined) {
  38834. needRebuild = true;
  38835. }
  38836. defines["LIGHT" + lightIndex] = true;
  38837. defines["SPOTLIGHT" + lightIndex] = false;
  38838. defines["HEMILIGHT" + lightIndex] = false;
  38839. defines["POINTLIGHT" + lightIndex] = false;
  38840. defines["DIRLIGHT" + lightIndex] = false;
  38841. var type;
  38842. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  38843. type = "SPOTLIGHT" + lightIndex;
  38844. var spotLight = light;
  38845. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  38846. }
  38847. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  38848. type = "HEMILIGHT" + lightIndex;
  38849. }
  38850. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  38851. type = "POINTLIGHT" + lightIndex;
  38852. }
  38853. else {
  38854. type = "DIRLIGHT" + lightIndex;
  38855. }
  38856. defines[type] = true;
  38857. // Specular
  38858. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  38859. specularEnabled = true;
  38860. }
  38861. // Shadows
  38862. defines["SHADOW" + lightIndex] = false;
  38863. defines["SHADOWPCF" + lightIndex] = false;
  38864. defines["SHADOWPCSS" + lightIndex] = false;
  38865. defines["SHADOWPOISSON" + lightIndex] = false;
  38866. defines["SHADOWESM" + lightIndex] = false;
  38867. defines["SHADOWCUBE" + lightIndex] = false;
  38868. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  38869. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  38870. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  38871. var shadowGenerator = light.getShadowGenerator();
  38872. if (shadowGenerator) {
  38873. shadowEnabled = true;
  38874. shadowGenerator.prepareDefines(defines, lightIndex);
  38875. }
  38876. }
  38877. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  38878. lightmapMode = true;
  38879. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  38880. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  38881. }
  38882. else {
  38883. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  38884. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  38885. }
  38886. lightIndex++;
  38887. if (lightIndex === maxSimultaneousLights)
  38888. break;
  38889. }
  38890. }
  38891. defines["SPECULARTERM"] = specularEnabled;
  38892. defines["SHADOWS"] = shadowEnabled;
  38893. // Resetting all other lights if any
  38894. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  38895. if (defines["LIGHT" + index] !== undefined) {
  38896. defines["LIGHT" + index] = false;
  38897. defines["HEMILIGHT" + lightIndex] = false;
  38898. defines["POINTLIGHT" + lightIndex] = false;
  38899. defines["DIRLIGHT" + lightIndex] = false;
  38900. defines["SPOTLIGHT" + lightIndex] = false;
  38901. defines["SHADOW" + lightIndex] = false;
  38902. }
  38903. }
  38904. var caps = scene.getEngine().getCaps();
  38905. if (defines["SHADOWFLOAT"] === undefined) {
  38906. needRebuild = true;
  38907. }
  38908. defines["SHADOWFLOAT"] = shadowEnabled &&
  38909. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  38910. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  38911. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  38912. if (needRebuild) {
  38913. defines.rebuild();
  38914. }
  38915. return needNormals;
  38916. };
  38917. /**
  38918. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  38919. * that won t be acctive due to defines being turned off.
  38920. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  38921. * @param samplersList The samplers list
  38922. * @param defines The defines helping in the list generation
  38923. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  38924. */
  38925. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  38926. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38927. var uniformsList;
  38928. var uniformBuffersList = null;
  38929. if (uniformsListOrOptions.uniformsNames) {
  38930. var options = uniformsListOrOptions;
  38931. uniformsList = options.uniformsNames;
  38932. uniformBuffersList = options.uniformBuffersNames;
  38933. samplersList = options.samplers;
  38934. defines = options.defines;
  38935. maxSimultaneousLights = options.maxSimultaneousLights;
  38936. }
  38937. else {
  38938. uniformsList = uniformsListOrOptions;
  38939. if (!samplersList) {
  38940. samplersList = [];
  38941. }
  38942. }
  38943. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38944. if (!defines["LIGHT" + lightIndex]) {
  38945. break;
  38946. }
  38947. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  38948. if (uniformBuffersList) {
  38949. uniformBuffersList.push("Light" + lightIndex);
  38950. }
  38951. samplersList.push("shadowSampler" + lightIndex);
  38952. samplersList.push("depthSampler" + lightIndex);
  38953. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  38954. samplersList.push("projectionLightSampler" + lightIndex);
  38955. uniformsList.push("textureProjectionMatrix" + lightIndex);
  38956. }
  38957. }
  38958. if (defines["NUM_MORPH_INFLUENCERS"]) {
  38959. uniformsList.push("morphTargetInfluences");
  38960. }
  38961. };
  38962. /**
  38963. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  38964. * @param defines The defines to update while falling back
  38965. * @param fallbacks The authorized effect fallbacks
  38966. * @param maxSimultaneousLights The maximum number of lights allowed
  38967. * @param rank the current rank of the Effect
  38968. * @returns The newly affected rank
  38969. */
  38970. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  38971. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38972. if (rank === void 0) { rank = 0; }
  38973. var lightFallbackRank = 0;
  38974. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38975. if (!defines["LIGHT" + lightIndex]) {
  38976. break;
  38977. }
  38978. if (lightIndex > 0) {
  38979. lightFallbackRank = rank + lightIndex;
  38980. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  38981. }
  38982. if (!defines["SHADOWS"]) {
  38983. if (defines["SHADOW" + lightIndex]) {
  38984. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  38985. }
  38986. if (defines["SHADOWPCF" + lightIndex]) {
  38987. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  38988. }
  38989. if (defines["SHADOWPCSS" + lightIndex]) {
  38990. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  38991. }
  38992. if (defines["SHADOWPOISSON" + lightIndex]) {
  38993. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  38994. }
  38995. if (defines["SHADOWESM" + lightIndex]) {
  38996. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  38997. }
  38998. }
  38999. }
  39000. return lightFallbackRank++;
  39001. };
  39002. /**
  39003. * Prepares the list of attributes required for morph targets according to the effect defines.
  39004. * @param attribs The current list of supported attribs
  39005. * @param mesh The mesh to prepare the morph targets attributes for
  39006. * @param defines The current Defines of the effect
  39007. */
  39008. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  39009. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  39010. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  39011. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  39012. var manager = mesh.morphTargetManager;
  39013. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  39014. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  39015. for (var index = 0; index < influencers; index++) {
  39016. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  39017. if (normal) {
  39018. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  39019. }
  39020. if (tangent) {
  39021. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  39022. }
  39023. if (attribs.length > maxAttributesCount) {
  39024. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  39025. }
  39026. }
  39027. }
  39028. };
  39029. /**
  39030. * Prepares the list of attributes required for bones according to the effect defines.
  39031. * @param attribs The current list of supported attribs
  39032. * @param mesh The mesh to prepare the bones attributes for
  39033. * @param defines The current Defines of the effect
  39034. * @param fallbacks The current efffect fallback strategy
  39035. */
  39036. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  39037. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  39038. fallbacks.addCPUSkinningFallback(0, mesh);
  39039. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39040. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39041. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  39042. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39043. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  39044. }
  39045. }
  39046. };
  39047. /**
  39048. * Prepares the list of attributes required for instances according to the effect defines.
  39049. * @param attribs The current list of supported attribs
  39050. * @param defines The current Defines of the effect
  39051. */
  39052. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  39053. if (defines["INSTANCES"]) {
  39054. attribs.push("world0");
  39055. attribs.push("world1");
  39056. attribs.push("world2");
  39057. attribs.push("world3");
  39058. }
  39059. };
  39060. /**
  39061. * Binds the light shadow information to the effect for the given mesh.
  39062. * @param light The light containing the generator
  39063. * @param scene The scene the lights belongs to
  39064. * @param mesh The mesh we are binding the information to render
  39065. * @param lightIndex The light index in the effect used to render the mesh
  39066. * @param effect The effect we are binding the data to
  39067. */
  39068. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  39069. if (light.shadowEnabled && mesh.receiveShadows) {
  39070. var shadowGenerator = light.getShadowGenerator();
  39071. if (shadowGenerator) {
  39072. shadowGenerator.bindShadowLight(lightIndex, effect);
  39073. }
  39074. }
  39075. };
  39076. /**
  39077. * Binds the light information to the effect.
  39078. * @param light The light containing the generator
  39079. * @param effect The effect we are binding the data to
  39080. * @param lightIndex The light index in the effect used to render
  39081. */
  39082. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  39083. light.transferToEffect(effect, lightIndex + "");
  39084. };
  39085. /**
  39086. * Binds the lights information from the scene to the effect for the given mesh.
  39087. * @param scene The scene the lights belongs to
  39088. * @param mesh The mesh we are binding the information to render
  39089. * @param effect The effect we are binding the data to
  39090. * @param defines The generated defines for the effect
  39091. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  39092. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  39093. */
  39094. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  39095. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39096. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  39097. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  39098. for (var i = 0; i < len; i++) {
  39099. var light = mesh._lightSources[i];
  39100. var iAsString = i.toString();
  39101. var scaledIntensity = light.getScaledIntensity();
  39102. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  39103. MaterialHelper.BindLightProperties(light, effect, i);
  39104. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  39105. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  39106. if (defines["SPECULARTERM"]) {
  39107. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  39108. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  39109. }
  39110. // Shadows
  39111. if (scene.shadowsEnabled) {
  39112. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  39113. }
  39114. light._uniformBuffer.update();
  39115. }
  39116. };
  39117. /**
  39118. * Binds the fog information from the scene to the effect for the given mesh.
  39119. * @param scene The scene the lights belongs to
  39120. * @param mesh The mesh we are binding the information to render
  39121. * @param effect The effect we are binding the data to
  39122. */
  39123. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  39124. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  39125. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  39126. effect.setColor3("vFogColor", scene.fogColor);
  39127. }
  39128. };
  39129. /**
  39130. * Binds the bones information from the mesh to the effect.
  39131. * @param mesh The mesh we are binding the information to render
  39132. * @param effect The effect we are binding the data to
  39133. */
  39134. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  39135. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  39136. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  39137. if (matrices && effect) {
  39138. effect.setMatrices("mBones", matrices);
  39139. }
  39140. }
  39141. };
  39142. /**
  39143. * Binds the morph targets information from the mesh to the effect.
  39144. * @param abstractMesh The mesh we are binding the information to render
  39145. * @param effect The effect we are binding the data to
  39146. */
  39147. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  39148. var manager = abstractMesh.morphTargetManager;
  39149. if (!abstractMesh || !manager) {
  39150. return;
  39151. }
  39152. effect.setFloatArray("morphTargetInfluences", manager.influences);
  39153. };
  39154. /**
  39155. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  39156. * @param defines The generated defines used in the effect
  39157. * @param effect The effect we are binding the data to
  39158. * @param scene The scene we are willing to render with logarithmic scale for
  39159. */
  39160. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  39161. if (defines["LOGARITHMICDEPTH"]) {
  39162. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  39163. }
  39164. };
  39165. /**
  39166. * Binds the clip plane information from the scene to the effect.
  39167. * @param scene The scene the clip plane information are extracted from
  39168. * @param effect The effect we are binding the data to
  39169. */
  39170. MaterialHelper.BindClipPlane = function (effect, scene) {
  39171. if (scene.clipPlane) {
  39172. var clipPlane = scene.clipPlane;
  39173. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  39174. }
  39175. };
  39176. return MaterialHelper;
  39177. }());
  39178. BABYLON.MaterialHelper = MaterialHelper;
  39179. })(BABYLON || (BABYLON = {}));
  39180. //# sourceMappingURL=babylon.materialHelper.js.map
  39181. var BABYLON;
  39182. (function (BABYLON) {
  39183. var PushMaterial = /** @class */ (function (_super) {
  39184. __extends(PushMaterial, _super);
  39185. function PushMaterial(name, scene) {
  39186. var _this = _super.call(this, name, scene) || this;
  39187. _this._normalMatrix = new BABYLON.Matrix();
  39188. _this.storeEffectOnSubMeshes = true;
  39189. return _this;
  39190. }
  39191. PushMaterial.prototype.getEffect = function () {
  39192. return this._activeEffect;
  39193. };
  39194. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  39195. if (!mesh) {
  39196. return false;
  39197. }
  39198. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  39199. return true;
  39200. }
  39201. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  39202. };
  39203. /**
  39204. * Binds the given world matrix to the active effect
  39205. *
  39206. * @param world the matrix to bind
  39207. */
  39208. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39209. this._activeEffect.setMatrix("world", world);
  39210. };
  39211. /**
  39212. * Binds the given normal matrix to the active effect
  39213. *
  39214. * @param normalMatrix the matrix to bind
  39215. */
  39216. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  39217. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  39218. };
  39219. PushMaterial.prototype.bind = function (world, mesh) {
  39220. if (!mesh) {
  39221. return;
  39222. }
  39223. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  39224. };
  39225. PushMaterial.prototype._afterBind = function (mesh, effect) {
  39226. if (effect === void 0) { effect = null; }
  39227. _super.prototype._afterBind.call(this, mesh);
  39228. this.getScene()._cachedEffect = effect;
  39229. };
  39230. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  39231. if (visibility === void 0) { visibility = 1; }
  39232. return scene.isCachedMaterialInvalid(this, effect, visibility);
  39233. };
  39234. return PushMaterial;
  39235. }(BABYLON.Material));
  39236. BABYLON.PushMaterial = PushMaterial;
  39237. })(BABYLON || (BABYLON = {}));
  39238. //# sourceMappingURL=babylon.pushMaterial.js.map
  39239. var BABYLON;
  39240. (function (BABYLON) {
  39241. /** @ignore */
  39242. var StandardMaterialDefines = /** @class */ (function (_super) {
  39243. __extends(StandardMaterialDefines, _super);
  39244. function StandardMaterialDefines() {
  39245. var _this = _super.call(this) || this;
  39246. _this.MAINUV1 = false;
  39247. _this.MAINUV2 = false;
  39248. _this.DIFFUSE = false;
  39249. _this.DIFFUSEDIRECTUV = 0;
  39250. _this.AMBIENT = false;
  39251. _this.AMBIENTDIRECTUV = 0;
  39252. _this.OPACITY = false;
  39253. _this.OPACITYDIRECTUV = 0;
  39254. _this.OPACITYRGB = false;
  39255. _this.REFLECTION = false;
  39256. _this.EMISSIVE = false;
  39257. _this.EMISSIVEDIRECTUV = 0;
  39258. _this.SPECULAR = false;
  39259. _this.SPECULARDIRECTUV = 0;
  39260. _this.BUMP = false;
  39261. _this.BUMPDIRECTUV = 0;
  39262. _this.PARALLAX = false;
  39263. _this.PARALLAXOCCLUSION = false;
  39264. _this.SPECULAROVERALPHA = false;
  39265. _this.CLIPPLANE = false;
  39266. _this.ALPHATEST = false;
  39267. _this.DEPTHPREPASS = false;
  39268. _this.ALPHAFROMDIFFUSE = false;
  39269. _this.POINTSIZE = false;
  39270. _this.FOG = false;
  39271. _this.SPECULARTERM = false;
  39272. _this.DIFFUSEFRESNEL = false;
  39273. _this.OPACITYFRESNEL = false;
  39274. _this.REFLECTIONFRESNEL = false;
  39275. _this.REFRACTIONFRESNEL = false;
  39276. _this.EMISSIVEFRESNEL = false;
  39277. _this.FRESNEL = false;
  39278. _this.NORMAL = false;
  39279. _this.UV1 = false;
  39280. _this.UV2 = false;
  39281. _this.VERTEXCOLOR = false;
  39282. _this.VERTEXALPHA = false;
  39283. _this.NUM_BONE_INFLUENCERS = 0;
  39284. _this.BonesPerMesh = 0;
  39285. _this.INSTANCES = false;
  39286. _this.GLOSSINESS = false;
  39287. _this.ROUGHNESS = false;
  39288. _this.EMISSIVEASILLUMINATION = false;
  39289. _this.LINKEMISSIVEWITHDIFFUSE = false;
  39290. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  39291. _this.LIGHTMAP = false;
  39292. _this.LIGHTMAPDIRECTUV = 0;
  39293. _this.OBJECTSPACE_NORMALMAP = false;
  39294. _this.USELIGHTMAPASSHADOWMAP = false;
  39295. _this.REFLECTIONMAP_3D = false;
  39296. _this.REFLECTIONMAP_SPHERICAL = false;
  39297. _this.REFLECTIONMAP_PLANAR = false;
  39298. _this.REFLECTIONMAP_CUBIC = false;
  39299. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  39300. _this.REFLECTIONMAP_PROJECTION = false;
  39301. _this.REFLECTIONMAP_SKYBOX = false;
  39302. _this.REFLECTIONMAP_EXPLICIT = false;
  39303. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39304. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39305. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39306. _this.INVERTCUBICMAP = false;
  39307. _this.LOGARITHMICDEPTH = false;
  39308. _this.REFRACTION = false;
  39309. _this.REFRACTIONMAP_3D = false;
  39310. _this.REFLECTIONOVERALPHA = false;
  39311. _this.TWOSIDEDLIGHTING = false;
  39312. _this.SHADOWFLOAT = false;
  39313. _this.MORPHTARGETS = false;
  39314. _this.MORPHTARGETS_NORMAL = false;
  39315. _this.MORPHTARGETS_TANGENT = false;
  39316. _this.NUM_MORPH_INFLUENCERS = 0;
  39317. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  39318. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  39319. _this.IMAGEPROCESSING = false;
  39320. _this.VIGNETTE = false;
  39321. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39322. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39323. _this.TONEMAPPING = false;
  39324. _this.CONTRAST = false;
  39325. _this.COLORCURVES = false;
  39326. _this.COLORGRADING = false;
  39327. _this.COLORGRADING3D = false;
  39328. _this.SAMPLER3DGREENDEPTH = false;
  39329. _this.SAMPLER3DBGRMAP = false;
  39330. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39331. _this.EXPOSURE = false;
  39332. _this.GRAIN = false;
  39333. _this.rebuild();
  39334. return _this;
  39335. }
  39336. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  39337. var modes = [
  39338. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  39339. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  39340. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  39341. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  39342. ];
  39343. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  39344. var mode = modes_1[_i];
  39345. this[mode] = (mode === modeToEnable);
  39346. }
  39347. };
  39348. return StandardMaterialDefines;
  39349. }(BABYLON.MaterialDefines));
  39350. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  39351. var StandardMaterial = /** @class */ (function (_super) {
  39352. __extends(StandardMaterial, _super);
  39353. function StandardMaterial(name, scene) {
  39354. var _this = _super.call(this, name, scene) || this;
  39355. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39356. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  39357. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  39358. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39359. _this.specularPower = 64;
  39360. _this._useAlphaFromDiffuseTexture = false;
  39361. _this._useEmissiveAsIllumination = false;
  39362. _this._linkEmissiveWithDiffuse = false;
  39363. _this._useSpecularOverAlpha = false;
  39364. _this._useReflectionOverAlpha = false;
  39365. _this._disableLighting = false;
  39366. _this._useObjectSpaceNormalMap = false;
  39367. _this._useParallax = false;
  39368. _this._useParallaxOcclusion = false;
  39369. _this.parallaxScaleBias = 0.05;
  39370. _this._roughness = 0;
  39371. _this.indexOfRefraction = 0.98;
  39372. _this.invertRefractionY = true;
  39373. _this._useLightmapAsShadowmap = false;
  39374. _this._useReflectionFresnelFromSpecular = false;
  39375. _this._useGlossinessFromSpecularMapAlpha = false;
  39376. _this._maxSimultaneousLights = 4;
  39377. /**
  39378. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39379. */
  39380. _this._invertNormalMapX = false;
  39381. /**
  39382. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39383. */
  39384. _this._invertNormalMapY = false;
  39385. /**
  39386. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39387. */
  39388. _this._twoSidedLighting = false;
  39389. _this._renderTargets = new BABYLON.SmartArray(16);
  39390. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  39391. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39392. // Setup the default processing configuration to the scene.
  39393. _this._attachImageProcessingConfiguration(null);
  39394. _this.getRenderTargetTextures = function () {
  39395. _this._renderTargets.reset();
  39396. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39397. _this._renderTargets.push(_this._reflectionTexture);
  39398. }
  39399. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39400. _this._renderTargets.push(_this._refractionTexture);
  39401. }
  39402. return _this._renderTargets;
  39403. };
  39404. return _this;
  39405. }
  39406. ;
  39407. ;
  39408. ;
  39409. ;
  39410. ;
  39411. ;
  39412. ;
  39413. ;
  39414. ;
  39415. ;
  39416. ;
  39417. ;
  39418. ;
  39419. ;
  39420. ;
  39421. ;
  39422. ;
  39423. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  39424. /**
  39425. * Gets the image processing configuration used either in this material.
  39426. */
  39427. get: function () {
  39428. return this._imageProcessingConfiguration;
  39429. },
  39430. /**
  39431. * Sets the Default image processing configuration used either in the this material.
  39432. *
  39433. * If sets to null, the scene one is in use.
  39434. */
  39435. set: function (value) {
  39436. this._attachImageProcessingConfiguration(value);
  39437. // Ensure the effect will be rebuilt.
  39438. this._markAllSubMeshesAsTexturesDirty();
  39439. },
  39440. enumerable: true,
  39441. configurable: true
  39442. });
  39443. /**
  39444. * Attaches a new image processing configuration to the Standard Material.
  39445. * @param configuration
  39446. */
  39447. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39448. var _this = this;
  39449. if (configuration === this._imageProcessingConfiguration) {
  39450. return;
  39451. }
  39452. // Detaches observer.
  39453. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39454. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39455. }
  39456. // Pick the scene configuration if needed.
  39457. if (!configuration) {
  39458. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  39459. }
  39460. else {
  39461. this._imageProcessingConfiguration = configuration;
  39462. }
  39463. // Attaches observer.
  39464. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39465. _this._markAllSubMeshesAsImageProcessingDirty();
  39466. });
  39467. };
  39468. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  39469. /**
  39470. * Gets wether the color curves effect is enabled.
  39471. */
  39472. get: function () {
  39473. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39474. },
  39475. /**
  39476. * Sets wether the color curves effect is enabled.
  39477. */
  39478. set: function (value) {
  39479. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39480. },
  39481. enumerable: true,
  39482. configurable: true
  39483. });
  39484. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  39485. /**
  39486. * Gets wether the color grading effect is enabled.
  39487. */
  39488. get: function () {
  39489. return this.imageProcessingConfiguration.colorGradingEnabled;
  39490. },
  39491. /**
  39492. * Gets wether the color grading effect is enabled.
  39493. */
  39494. set: function (value) {
  39495. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39496. },
  39497. enumerable: true,
  39498. configurable: true
  39499. });
  39500. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  39501. /**
  39502. * Gets wether tonemapping is enabled or not.
  39503. */
  39504. get: function () {
  39505. return this._imageProcessingConfiguration.toneMappingEnabled;
  39506. },
  39507. /**
  39508. * Sets wether tonemapping is enabled or not
  39509. */
  39510. set: function (value) {
  39511. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39512. },
  39513. enumerable: true,
  39514. configurable: true
  39515. });
  39516. ;
  39517. ;
  39518. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  39519. /**
  39520. * The camera exposure used on this material.
  39521. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39522. * This corresponds to a photographic exposure.
  39523. */
  39524. get: function () {
  39525. return this._imageProcessingConfiguration.exposure;
  39526. },
  39527. /**
  39528. * The camera exposure used on this material.
  39529. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39530. * This corresponds to a photographic exposure.
  39531. */
  39532. set: function (value) {
  39533. this._imageProcessingConfiguration.exposure = value;
  39534. },
  39535. enumerable: true,
  39536. configurable: true
  39537. });
  39538. ;
  39539. ;
  39540. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  39541. /**
  39542. * Gets The camera contrast used on this material.
  39543. */
  39544. get: function () {
  39545. return this._imageProcessingConfiguration.contrast;
  39546. },
  39547. /**
  39548. * Sets The camera contrast used on this material.
  39549. */
  39550. set: function (value) {
  39551. this._imageProcessingConfiguration.contrast = value;
  39552. },
  39553. enumerable: true,
  39554. configurable: true
  39555. });
  39556. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  39557. /**
  39558. * Gets the Color Grading 2D Lookup Texture.
  39559. */
  39560. get: function () {
  39561. return this._imageProcessingConfiguration.colorGradingTexture;
  39562. },
  39563. /**
  39564. * Sets the Color Grading 2D Lookup Texture.
  39565. */
  39566. set: function (value) {
  39567. this._imageProcessingConfiguration.colorGradingTexture = value;
  39568. },
  39569. enumerable: true,
  39570. configurable: true
  39571. });
  39572. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39573. /**
  39574. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39575. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39576. * 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;
  39577. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39578. */
  39579. get: function () {
  39580. return this._imageProcessingConfiguration.colorCurves;
  39581. },
  39582. /**
  39583. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39584. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39585. * 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;
  39586. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39587. */
  39588. set: function (value) {
  39589. this._imageProcessingConfiguration.colorCurves = value;
  39590. },
  39591. enumerable: true,
  39592. configurable: true
  39593. });
  39594. StandardMaterial.prototype.getClassName = function () {
  39595. return "StandardMaterial";
  39596. };
  39597. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39598. get: function () {
  39599. return this._useLogarithmicDepth;
  39600. },
  39601. set: function (value) {
  39602. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39603. this._markAllSubMeshesAsMiscDirty();
  39604. },
  39605. enumerable: true,
  39606. configurable: true
  39607. });
  39608. StandardMaterial.prototype.needAlphaBlending = function () {
  39609. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39610. };
  39611. StandardMaterial.prototype.needAlphaTesting = function () {
  39612. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39613. };
  39614. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39615. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39616. };
  39617. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39618. return this._diffuseTexture;
  39619. };
  39620. /**
  39621. * Child classes can use it to update shaders
  39622. */
  39623. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39624. if (useInstances === void 0) { useInstances = false; }
  39625. if (subMesh.effect && this.isFrozen) {
  39626. if (this._wasPreviouslyReady && subMesh.effect) {
  39627. return true;
  39628. }
  39629. }
  39630. if (!subMesh._materialDefines) {
  39631. subMesh._materialDefines = new StandardMaterialDefines();
  39632. }
  39633. var scene = this.getScene();
  39634. var defines = subMesh._materialDefines;
  39635. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39636. if (defines._renderId === scene.getRenderId()) {
  39637. return true;
  39638. }
  39639. }
  39640. var engine = scene.getEngine();
  39641. // Lights
  39642. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39643. // Textures
  39644. if (defines._areTexturesDirty) {
  39645. defines._needUVs = false;
  39646. defines.MAINUV1 = false;
  39647. defines.MAINUV2 = false;
  39648. if (scene.texturesEnabled) {
  39649. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39650. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39651. return false;
  39652. }
  39653. else {
  39654. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39655. }
  39656. }
  39657. else {
  39658. defines.DIFFUSE = false;
  39659. }
  39660. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39661. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39662. return false;
  39663. }
  39664. else {
  39665. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39666. }
  39667. }
  39668. else {
  39669. defines.AMBIENT = false;
  39670. }
  39671. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39672. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39673. return false;
  39674. }
  39675. else {
  39676. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39677. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39678. }
  39679. }
  39680. else {
  39681. defines.OPACITY = false;
  39682. }
  39683. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39684. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39685. return false;
  39686. }
  39687. else {
  39688. defines._needNormals = true;
  39689. defines.REFLECTION = true;
  39690. defines.ROUGHNESS = (this._roughness > 0);
  39691. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39692. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39693. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39694. switch (this._reflectionTexture.coordinatesMode) {
  39695. case BABYLON.Texture.CUBIC_MODE:
  39696. case BABYLON.Texture.INVCUBIC_MODE:
  39697. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39698. break;
  39699. case BABYLON.Texture.EXPLICIT_MODE:
  39700. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39701. break;
  39702. case BABYLON.Texture.PLANAR_MODE:
  39703. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39704. break;
  39705. case BABYLON.Texture.PROJECTION_MODE:
  39706. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39707. break;
  39708. case BABYLON.Texture.SKYBOX_MODE:
  39709. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39710. break;
  39711. case BABYLON.Texture.SPHERICAL_MODE:
  39712. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39713. break;
  39714. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39715. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39716. break;
  39717. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39718. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39719. break;
  39720. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39721. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39722. break;
  39723. }
  39724. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39725. }
  39726. }
  39727. else {
  39728. defines.REFLECTION = false;
  39729. }
  39730. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39731. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39732. return false;
  39733. }
  39734. else {
  39735. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39736. }
  39737. }
  39738. else {
  39739. defines.EMISSIVE = false;
  39740. }
  39741. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39742. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39743. return false;
  39744. }
  39745. else {
  39746. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39747. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39748. }
  39749. }
  39750. else {
  39751. defines.LIGHTMAP = false;
  39752. }
  39753. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39754. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39755. return false;
  39756. }
  39757. else {
  39758. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39759. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39760. }
  39761. }
  39762. else {
  39763. defines.SPECULAR = false;
  39764. }
  39765. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39766. // Bump texure can not be not blocking.
  39767. if (!this._bumpTexture.isReady()) {
  39768. return false;
  39769. }
  39770. else {
  39771. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39772. defines.PARALLAX = this._useParallax;
  39773. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39774. }
  39775. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39776. }
  39777. else {
  39778. defines.BUMP = false;
  39779. }
  39780. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39781. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  39782. return false;
  39783. }
  39784. else {
  39785. defines._needUVs = true;
  39786. defines.REFRACTION = true;
  39787. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  39788. }
  39789. }
  39790. else {
  39791. defines.REFRACTION = false;
  39792. }
  39793. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  39794. }
  39795. else {
  39796. defines.DIFFUSE = false;
  39797. defines.AMBIENT = false;
  39798. defines.OPACITY = false;
  39799. defines.REFLECTION = false;
  39800. defines.EMISSIVE = false;
  39801. defines.LIGHTMAP = false;
  39802. defines.BUMP = false;
  39803. defines.REFRACTION = false;
  39804. }
  39805. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  39806. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  39807. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  39808. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39809. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39810. }
  39811. if (defines._areImageProcessingDirty) {
  39812. if (!this._imageProcessingConfiguration.isReady()) {
  39813. return false;
  39814. }
  39815. this._imageProcessingConfiguration.prepareDefines(defines);
  39816. }
  39817. if (defines._areFresnelDirty) {
  39818. if (StandardMaterial.FresnelEnabled) {
  39819. // Fresnel
  39820. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  39821. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  39822. this._reflectionFresnelParameters) {
  39823. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  39824. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  39825. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  39826. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  39827. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  39828. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  39829. defines._needNormals = true;
  39830. defines.FRESNEL = true;
  39831. }
  39832. }
  39833. else {
  39834. defines.FRESNEL = false;
  39835. }
  39836. }
  39837. // Misc.
  39838. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  39839. // Attribs
  39840. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  39841. // Values that need to be evaluated on every frame
  39842. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  39843. // Get correct effect
  39844. if (defines.isDirty) {
  39845. defines.markAsProcessed();
  39846. scene.resetCachedMaterial();
  39847. // Fallbacks
  39848. var fallbacks = new BABYLON.EffectFallbacks();
  39849. if (defines.REFLECTION) {
  39850. fallbacks.addFallback(0, "REFLECTION");
  39851. }
  39852. if (defines.SPECULAR) {
  39853. fallbacks.addFallback(0, "SPECULAR");
  39854. }
  39855. if (defines.BUMP) {
  39856. fallbacks.addFallback(0, "BUMP");
  39857. }
  39858. if (defines.PARALLAX) {
  39859. fallbacks.addFallback(1, "PARALLAX");
  39860. }
  39861. if (defines.PARALLAXOCCLUSION) {
  39862. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  39863. }
  39864. if (defines.SPECULAROVERALPHA) {
  39865. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  39866. }
  39867. if (defines.FOG) {
  39868. fallbacks.addFallback(1, "FOG");
  39869. }
  39870. if (defines.POINTSIZE) {
  39871. fallbacks.addFallback(0, "POINTSIZE");
  39872. }
  39873. if (defines.LOGARITHMICDEPTH) {
  39874. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  39875. }
  39876. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  39877. if (defines.SPECULARTERM) {
  39878. fallbacks.addFallback(0, "SPECULARTERM");
  39879. }
  39880. if (defines.DIFFUSEFRESNEL) {
  39881. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  39882. }
  39883. if (defines.OPACITYFRESNEL) {
  39884. fallbacks.addFallback(2, "OPACITYFRESNEL");
  39885. }
  39886. if (defines.REFLECTIONFRESNEL) {
  39887. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  39888. }
  39889. if (defines.EMISSIVEFRESNEL) {
  39890. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  39891. }
  39892. if (defines.FRESNEL) {
  39893. fallbacks.addFallback(4, "FRESNEL");
  39894. }
  39895. //Attributes
  39896. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39897. if (defines.NORMAL) {
  39898. attribs.push(BABYLON.VertexBuffer.NormalKind);
  39899. }
  39900. if (defines.UV1) {
  39901. attribs.push(BABYLON.VertexBuffer.UVKind);
  39902. }
  39903. if (defines.UV2) {
  39904. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39905. }
  39906. if (defines.VERTEXCOLOR) {
  39907. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39908. }
  39909. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  39910. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  39911. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  39912. var shaderName = "default";
  39913. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  39914. "vFogInfos", "vFogColor", "pointSize",
  39915. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  39916. "mBones",
  39917. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  39918. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  39919. "vReflectionPosition", "vReflectionSize",
  39920. "logarithmicDepthConstant", "vTangentSpaceParams"
  39921. ];
  39922. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  39923. var uniformBuffers = ["Material", "Scene"];
  39924. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  39925. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  39926. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39927. uniformsNames: uniforms,
  39928. uniformBuffersNames: uniformBuffers,
  39929. samplers: samplers,
  39930. defines: defines,
  39931. maxSimultaneousLights: this._maxSimultaneousLights
  39932. });
  39933. if (this.customShaderNameResolve) {
  39934. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  39935. }
  39936. var join = defines.toString();
  39937. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  39938. attributes: attribs,
  39939. uniformsNames: uniforms,
  39940. uniformBuffersNames: uniformBuffers,
  39941. samplers: samplers,
  39942. defines: join,
  39943. fallbacks: fallbacks,
  39944. onCompiled: this.onCompiled,
  39945. onError: this.onError,
  39946. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  39947. }, engine), defines);
  39948. this.buildUniformLayout();
  39949. }
  39950. if (!subMesh.effect || !subMesh.effect.isReady()) {
  39951. return false;
  39952. }
  39953. defines._renderId = scene.getRenderId();
  39954. this._wasPreviouslyReady = true;
  39955. return true;
  39956. };
  39957. StandardMaterial.prototype.buildUniformLayout = function () {
  39958. // Order is important !
  39959. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  39960. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  39961. this._uniformBuffer.addUniform("opacityParts", 4);
  39962. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  39963. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  39964. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  39965. this._uniformBuffer.addUniform("refractionRightColor", 4);
  39966. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  39967. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  39968. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  39969. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  39970. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  39971. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  39972. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  39973. this._uniformBuffer.addUniform("vReflectionSize", 3);
  39974. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  39975. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  39976. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  39977. this._uniformBuffer.addUniform("vBumpInfos", 3);
  39978. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  39979. this._uniformBuffer.addUniform("ambientMatrix", 16);
  39980. this._uniformBuffer.addUniform("opacityMatrix", 16);
  39981. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  39982. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  39983. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  39984. this._uniformBuffer.addUniform("specularMatrix", 16);
  39985. this._uniformBuffer.addUniform("bumpMatrix", 16);
  39986. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  39987. this._uniformBuffer.addUniform("refractionMatrix", 16);
  39988. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  39989. this._uniformBuffer.addUniform("vSpecularColor", 4);
  39990. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  39991. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  39992. this._uniformBuffer.addUniform("pointSize", 1);
  39993. this._uniformBuffer.create();
  39994. };
  39995. StandardMaterial.prototype.unbind = function () {
  39996. if (this._activeEffect) {
  39997. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  39998. this._activeEffect.setTexture("reflection2DSampler", null);
  39999. }
  40000. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  40001. this._activeEffect.setTexture("refraction2DSampler", null);
  40002. }
  40003. }
  40004. _super.prototype.unbind.call(this);
  40005. };
  40006. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  40007. var scene = this.getScene();
  40008. var defines = subMesh._materialDefines;
  40009. if (!defines) {
  40010. return;
  40011. }
  40012. var effect = subMesh.effect;
  40013. if (!effect) {
  40014. return;
  40015. }
  40016. this._activeEffect = effect;
  40017. // Matrices
  40018. this.bindOnlyWorldMatrix(world);
  40019. // Normal Matrix
  40020. if (defines.OBJECTSPACE_NORMALMAP) {
  40021. world.toNormalMatrix(this._normalMatrix);
  40022. this.bindOnlyNormalMatrix(this._normalMatrix);
  40023. }
  40024. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  40025. // Bones
  40026. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  40027. if (mustRebind) {
  40028. this._uniformBuffer.bindToEffect(effect, "Material");
  40029. this.bindViewProjection(effect);
  40030. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  40031. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  40032. // Fresnel
  40033. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  40034. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  40035. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  40036. }
  40037. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  40038. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  40039. }
  40040. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  40041. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  40042. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  40043. }
  40044. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  40045. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  40046. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  40047. }
  40048. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  40049. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  40050. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  40051. }
  40052. }
  40053. // Textures
  40054. if (scene.texturesEnabled) {
  40055. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40056. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  40057. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  40058. }
  40059. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40060. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  40061. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  40062. }
  40063. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40064. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  40065. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  40066. }
  40067. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40068. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  40069. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  40070. if (this._reflectionTexture.boundingBoxSize) {
  40071. var cubeTexture = this._reflectionTexture;
  40072. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  40073. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  40074. }
  40075. }
  40076. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40077. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  40078. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  40079. }
  40080. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40081. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  40082. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  40083. }
  40084. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40085. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  40086. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  40087. }
  40088. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  40089. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  40090. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  40091. if (scene._mirroredCameraPosition) {
  40092. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  40093. }
  40094. else {
  40095. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  40096. }
  40097. }
  40098. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40099. var depth = 1.0;
  40100. if (!this._refractionTexture.isCube) {
  40101. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  40102. if (this._refractionTexture.depth) {
  40103. depth = this._refractionTexture.depth;
  40104. }
  40105. }
  40106. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  40107. }
  40108. }
  40109. // Point size
  40110. if (this.pointsCloud) {
  40111. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  40112. }
  40113. if (defines.SPECULARTERM) {
  40114. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  40115. }
  40116. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  40117. // Diffuse
  40118. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  40119. }
  40120. // Textures
  40121. if (scene.texturesEnabled) {
  40122. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40123. effect.setTexture("diffuseSampler", this._diffuseTexture);
  40124. }
  40125. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40126. effect.setTexture("ambientSampler", this._ambientTexture);
  40127. }
  40128. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40129. effect.setTexture("opacitySampler", this._opacityTexture);
  40130. }
  40131. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40132. if (this._reflectionTexture.isCube) {
  40133. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  40134. }
  40135. else {
  40136. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  40137. }
  40138. }
  40139. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40140. effect.setTexture("emissiveSampler", this._emissiveTexture);
  40141. }
  40142. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40143. effect.setTexture("lightmapSampler", this._lightmapTexture);
  40144. }
  40145. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40146. effect.setTexture("specularSampler", this._specularTexture);
  40147. }
  40148. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  40149. effect.setTexture("bumpSampler", this._bumpTexture);
  40150. }
  40151. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40152. var depth = 1.0;
  40153. if (this._refractionTexture.isCube) {
  40154. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  40155. }
  40156. else {
  40157. effect.setTexture("refraction2DSampler", this._refractionTexture);
  40158. }
  40159. }
  40160. }
  40161. // Clip plane
  40162. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  40163. // Colors
  40164. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  40165. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  40166. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  40167. }
  40168. if (mustRebind || !this.isFrozen) {
  40169. // Lights
  40170. if (scene.lightsEnabled && !this._disableLighting) {
  40171. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  40172. }
  40173. // View
  40174. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  40175. this.bindView(effect);
  40176. }
  40177. // Fog
  40178. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  40179. // Morph targets
  40180. if (defines.NUM_MORPH_INFLUENCERS) {
  40181. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  40182. }
  40183. // Log. depth
  40184. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  40185. // image processing
  40186. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  40187. this._imageProcessingConfiguration.bind(this._activeEffect);
  40188. }
  40189. }
  40190. this._uniformBuffer.update();
  40191. this._afterBind(mesh, this._activeEffect);
  40192. };
  40193. StandardMaterial.prototype.getAnimatables = function () {
  40194. var results = [];
  40195. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  40196. results.push(this._diffuseTexture);
  40197. }
  40198. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  40199. results.push(this._ambientTexture);
  40200. }
  40201. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  40202. results.push(this._opacityTexture);
  40203. }
  40204. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  40205. results.push(this._reflectionTexture);
  40206. }
  40207. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  40208. results.push(this._emissiveTexture);
  40209. }
  40210. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  40211. results.push(this._specularTexture);
  40212. }
  40213. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  40214. results.push(this._bumpTexture);
  40215. }
  40216. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  40217. results.push(this._lightmapTexture);
  40218. }
  40219. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  40220. results.push(this._refractionTexture);
  40221. }
  40222. return results;
  40223. };
  40224. StandardMaterial.prototype.getActiveTextures = function () {
  40225. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40226. if (this._diffuseTexture) {
  40227. activeTextures.push(this._diffuseTexture);
  40228. }
  40229. if (this._ambientTexture) {
  40230. activeTextures.push(this._ambientTexture);
  40231. }
  40232. if (this._opacityTexture) {
  40233. activeTextures.push(this._opacityTexture);
  40234. }
  40235. if (this._reflectionTexture) {
  40236. activeTextures.push(this._reflectionTexture);
  40237. }
  40238. if (this._emissiveTexture) {
  40239. activeTextures.push(this._emissiveTexture);
  40240. }
  40241. if (this._specularTexture) {
  40242. activeTextures.push(this._specularTexture);
  40243. }
  40244. if (this._bumpTexture) {
  40245. activeTextures.push(this._bumpTexture);
  40246. }
  40247. if (this._lightmapTexture) {
  40248. activeTextures.push(this._lightmapTexture);
  40249. }
  40250. if (this._refractionTexture) {
  40251. activeTextures.push(this._refractionTexture);
  40252. }
  40253. return activeTextures;
  40254. };
  40255. StandardMaterial.prototype.hasTexture = function (texture) {
  40256. if (_super.prototype.hasTexture.call(this, texture)) {
  40257. return true;
  40258. }
  40259. if (this._diffuseTexture === texture) {
  40260. return true;
  40261. }
  40262. if (this._ambientTexture === texture) {
  40263. return true;
  40264. }
  40265. if (this._opacityTexture === texture) {
  40266. return true;
  40267. }
  40268. if (this._reflectionTexture === texture) {
  40269. return true;
  40270. }
  40271. if (this._emissiveTexture === texture) {
  40272. return true;
  40273. }
  40274. if (this._specularTexture === texture) {
  40275. return true;
  40276. }
  40277. if (this._bumpTexture === texture) {
  40278. return true;
  40279. }
  40280. if (this._lightmapTexture === texture) {
  40281. return true;
  40282. }
  40283. if (this._refractionTexture === texture) {
  40284. return true;
  40285. }
  40286. return false;
  40287. };
  40288. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40289. if (forceDisposeTextures) {
  40290. if (this._diffuseTexture) {
  40291. this._diffuseTexture.dispose();
  40292. }
  40293. if (this._ambientTexture) {
  40294. this._ambientTexture.dispose();
  40295. }
  40296. if (this._opacityTexture) {
  40297. this._opacityTexture.dispose();
  40298. }
  40299. if (this._reflectionTexture) {
  40300. this._reflectionTexture.dispose();
  40301. }
  40302. if (this._emissiveTexture) {
  40303. this._emissiveTexture.dispose();
  40304. }
  40305. if (this._specularTexture) {
  40306. this._specularTexture.dispose();
  40307. }
  40308. if (this._bumpTexture) {
  40309. this._bumpTexture.dispose();
  40310. }
  40311. if (this._lightmapTexture) {
  40312. this._lightmapTexture.dispose();
  40313. }
  40314. if (this._refractionTexture) {
  40315. this._refractionTexture.dispose();
  40316. }
  40317. }
  40318. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40319. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40320. }
  40321. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40322. };
  40323. StandardMaterial.prototype.clone = function (name) {
  40324. var _this = this;
  40325. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  40326. result.name = name;
  40327. result.id = name;
  40328. return result;
  40329. };
  40330. StandardMaterial.prototype.serialize = function () {
  40331. return BABYLON.SerializationHelper.Serialize(this);
  40332. };
  40333. // Statics
  40334. StandardMaterial.Parse = function (source, scene, rootUrl) {
  40335. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  40336. };
  40337. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  40338. get: function () {
  40339. return StandardMaterial._DiffuseTextureEnabled;
  40340. },
  40341. set: function (value) {
  40342. if (StandardMaterial._DiffuseTextureEnabled === value) {
  40343. return;
  40344. }
  40345. StandardMaterial._DiffuseTextureEnabled = value;
  40346. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40347. },
  40348. enumerable: true,
  40349. configurable: true
  40350. });
  40351. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  40352. get: function () {
  40353. return StandardMaterial._AmbientTextureEnabled;
  40354. },
  40355. set: function (value) {
  40356. if (StandardMaterial._AmbientTextureEnabled === value) {
  40357. return;
  40358. }
  40359. StandardMaterial._AmbientTextureEnabled = value;
  40360. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40361. },
  40362. enumerable: true,
  40363. configurable: true
  40364. });
  40365. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  40366. get: function () {
  40367. return StandardMaterial._OpacityTextureEnabled;
  40368. },
  40369. set: function (value) {
  40370. if (StandardMaterial._OpacityTextureEnabled === value) {
  40371. return;
  40372. }
  40373. StandardMaterial._OpacityTextureEnabled = value;
  40374. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40375. },
  40376. enumerable: true,
  40377. configurable: true
  40378. });
  40379. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  40380. get: function () {
  40381. return StandardMaterial._ReflectionTextureEnabled;
  40382. },
  40383. set: function (value) {
  40384. if (StandardMaterial._ReflectionTextureEnabled === value) {
  40385. return;
  40386. }
  40387. StandardMaterial._ReflectionTextureEnabled = value;
  40388. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40389. },
  40390. enumerable: true,
  40391. configurable: true
  40392. });
  40393. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  40394. get: function () {
  40395. return StandardMaterial._EmissiveTextureEnabled;
  40396. },
  40397. set: function (value) {
  40398. if (StandardMaterial._EmissiveTextureEnabled === value) {
  40399. return;
  40400. }
  40401. StandardMaterial._EmissiveTextureEnabled = value;
  40402. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40403. },
  40404. enumerable: true,
  40405. configurable: true
  40406. });
  40407. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  40408. get: function () {
  40409. return StandardMaterial._SpecularTextureEnabled;
  40410. },
  40411. set: function (value) {
  40412. if (StandardMaterial._SpecularTextureEnabled === value) {
  40413. return;
  40414. }
  40415. StandardMaterial._SpecularTextureEnabled = value;
  40416. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40417. },
  40418. enumerable: true,
  40419. configurable: true
  40420. });
  40421. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  40422. get: function () {
  40423. return StandardMaterial._BumpTextureEnabled;
  40424. },
  40425. set: function (value) {
  40426. if (StandardMaterial._BumpTextureEnabled === value) {
  40427. return;
  40428. }
  40429. StandardMaterial._BumpTextureEnabled = value;
  40430. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40431. },
  40432. enumerable: true,
  40433. configurable: true
  40434. });
  40435. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  40436. get: function () {
  40437. return StandardMaterial._LightmapTextureEnabled;
  40438. },
  40439. set: function (value) {
  40440. if (StandardMaterial._LightmapTextureEnabled === value) {
  40441. return;
  40442. }
  40443. StandardMaterial._LightmapTextureEnabled = value;
  40444. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40445. },
  40446. enumerable: true,
  40447. configurable: true
  40448. });
  40449. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  40450. get: function () {
  40451. return StandardMaterial._RefractionTextureEnabled;
  40452. },
  40453. set: function (value) {
  40454. if (StandardMaterial._RefractionTextureEnabled === value) {
  40455. return;
  40456. }
  40457. StandardMaterial._RefractionTextureEnabled = value;
  40458. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40459. },
  40460. enumerable: true,
  40461. configurable: true
  40462. });
  40463. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  40464. get: function () {
  40465. return StandardMaterial._ColorGradingTextureEnabled;
  40466. },
  40467. set: function (value) {
  40468. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  40469. return;
  40470. }
  40471. StandardMaterial._ColorGradingTextureEnabled = value;
  40472. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40473. },
  40474. enumerable: true,
  40475. configurable: true
  40476. });
  40477. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  40478. get: function () {
  40479. return StandardMaterial._FresnelEnabled;
  40480. },
  40481. set: function (value) {
  40482. if (StandardMaterial._FresnelEnabled === value) {
  40483. return;
  40484. }
  40485. StandardMaterial._FresnelEnabled = value;
  40486. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  40487. },
  40488. enumerable: true,
  40489. configurable: true
  40490. });
  40491. // Flags used to enable or disable a type of texture for all Standard Materials
  40492. StandardMaterial._DiffuseTextureEnabled = true;
  40493. StandardMaterial._AmbientTextureEnabled = true;
  40494. StandardMaterial._OpacityTextureEnabled = true;
  40495. StandardMaterial._ReflectionTextureEnabled = true;
  40496. StandardMaterial._EmissiveTextureEnabled = true;
  40497. StandardMaterial._SpecularTextureEnabled = true;
  40498. StandardMaterial._BumpTextureEnabled = true;
  40499. StandardMaterial._LightmapTextureEnabled = true;
  40500. StandardMaterial._RefractionTextureEnabled = true;
  40501. StandardMaterial._ColorGradingTextureEnabled = true;
  40502. StandardMaterial._FresnelEnabled = true;
  40503. __decorate([
  40504. BABYLON.serializeAsTexture("diffuseTexture")
  40505. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  40506. __decorate([
  40507. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40508. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  40509. __decorate([
  40510. BABYLON.serializeAsTexture("ambientTexture")
  40511. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  40512. __decorate([
  40513. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40514. ], StandardMaterial.prototype, "ambientTexture", void 0);
  40515. __decorate([
  40516. BABYLON.serializeAsTexture("opacityTexture")
  40517. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  40518. __decorate([
  40519. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40520. ], StandardMaterial.prototype, "opacityTexture", void 0);
  40521. __decorate([
  40522. BABYLON.serializeAsTexture("reflectionTexture")
  40523. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  40524. __decorate([
  40525. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40526. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  40527. __decorate([
  40528. BABYLON.serializeAsTexture("emissiveTexture")
  40529. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  40530. __decorate([
  40531. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40532. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  40533. __decorate([
  40534. BABYLON.serializeAsTexture("specularTexture")
  40535. ], StandardMaterial.prototype, "_specularTexture", void 0);
  40536. __decorate([
  40537. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40538. ], StandardMaterial.prototype, "specularTexture", void 0);
  40539. __decorate([
  40540. BABYLON.serializeAsTexture("bumpTexture")
  40541. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  40542. __decorate([
  40543. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40544. ], StandardMaterial.prototype, "bumpTexture", void 0);
  40545. __decorate([
  40546. BABYLON.serializeAsTexture("lightmapTexture")
  40547. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  40548. __decorate([
  40549. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40550. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  40551. __decorate([
  40552. BABYLON.serializeAsTexture("refractionTexture")
  40553. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  40554. __decorate([
  40555. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40556. ], StandardMaterial.prototype, "refractionTexture", void 0);
  40557. __decorate([
  40558. BABYLON.serializeAsColor3("ambient")
  40559. ], StandardMaterial.prototype, "ambientColor", void 0);
  40560. __decorate([
  40561. BABYLON.serializeAsColor3("diffuse")
  40562. ], StandardMaterial.prototype, "diffuseColor", void 0);
  40563. __decorate([
  40564. BABYLON.serializeAsColor3("specular")
  40565. ], StandardMaterial.prototype, "specularColor", void 0);
  40566. __decorate([
  40567. BABYLON.serializeAsColor3("emissive")
  40568. ], StandardMaterial.prototype, "emissiveColor", void 0);
  40569. __decorate([
  40570. BABYLON.serialize()
  40571. ], StandardMaterial.prototype, "specularPower", void 0);
  40572. __decorate([
  40573. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40574. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40575. __decorate([
  40576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40577. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40578. __decorate([
  40579. BABYLON.serialize("useEmissiveAsIllumination")
  40580. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40581. __decorate([
  40582. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40583. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40584. __decorate([
  40585. BABYLON.serialize("linkEmissiveWithDiffuse")
  40586. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40587. __decorate([
  40588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40589. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40590. __decorate([
  40591. BABYLON.serialize("useSpecularOverAlpha")
  40592. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40593. __decorate([
  40594. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40595. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40596. __decorate([
  40597. BABYLON.serialize("useReflectionOverAlpha")
  40598. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40599. __decorate([
  40600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40601. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40602. __decorate([
  40603. BABYLON.serialize("disableLighting")
  40604. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40605. __decorate([
  40606. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40607. ], StandardMaterial.prototype, "disableLighting", void 0);
  40608. __decorate([
  40609. BABYLON.serialize("useObjectSpaceNormalMap")
  40610. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40611. __decorate([
  40612. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40613. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40614. __decorate([
  40615. BABYLON.serialize("useParallax")
  40616. ], StandardMaterial.prototype, "_useParallax", void 0);
  40617. __decorate([
  40618. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40619. ], StandardMaterial.prototype, "useParallax", void 0);
  40620. __decorate([
  40621. BABYLON.serialize("useParallaxOcclusion")
  40622. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40623. __decorate([
  40624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40625. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40626. __decorate([
  40627. BABYLON.serialize()
  40628. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40629. __decorate([
  40630. BABYLON.serialize("roughness")
  40631. ], StandardMaterial.prototype, "_roughness", void 0);
  40632. __decorate([
  40633. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40634. ], StandardMaterial.prototype, "roughness", void 0);
  40635. __decorate([
  40636. BABYLON.serialize()
  40637. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40638. __decorate([
  40639. BABYLON.serialize()
  40640. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40641. __decorate([
  40642. BABYLON.serialize("useLightmapAsShadowmap")
  40643. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40644. __decorate([
  40645. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40646. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40647. __decorate([
  40648. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40649. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40650. __decorate([
  40651. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40652. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40653. __decorate([
  40654. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40655. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40656. __decorate([
  40657. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40658. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40659. __decorate([
  40660. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40661. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40662. __decorate([
  40663. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40664. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40665. __decorate([
  40666. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40667. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40668. __decorate([
  40669. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40670. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40671. __decorate([
  40672. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40673. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40674. __decorate([
  40675. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40676. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40677. __decorate([
  40678. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40679. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40680. __decorate([
  40681. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40682. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40683. __decorate([
  40684. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40685. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40686. __decorate([
  40687. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40688. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40689. __decorate([
  40690. BABYLON.serialize("maxSimultaneousLights")
  40691. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40692. __decorate([
  40693. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40694. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40695. __decorate([
  40696. BABYLON.serialize("invertNormalMapX")
  40697. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40698. __decorate([
  40699. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40700. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40701. __decorate([
  40702. BABYLON.serialize("invertNormalMapY")
  40703. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40704. __decorate([
  40705. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40706. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40707. __decorate([
  40708. BABYLON.serialize("twoSidedLighting")
  40709. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40710. __decorate([
  40711. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40712. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40713. __decorate([
  40714. BABYLON.serialize()
  40715. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40716. return StandardMaterial;
  40717. }(BABYLON.PushMaterial));
  40718. BABYLON.StandardMaterial = StandardMaterial;
  40719. })(BABYLON || (BABYLON = {}));
  40720. //# sourceMappingURL=babylon.standardMaterial.js.map
  40721. var BABYLON;
  40722. (function (BABYLON) {
  40723. /**
  40724. * Manages the defines for the PBR Material.
  40725. */
  40726. var PBRMaterialDefines = /** @class */ (function (_super) {
  40727. __extends(PBRMaterialDefines, _super);
  40728. /**
  40729. * Initializes the PBR Material defines.
  40730. */
  40731. function PBRMaterialDefines() {
  40732. var _this = _super.call(this) || this;
  40733. _this.PBR = true;
  40734. _this.MAINUV1 = false;
  40735. _this.MAINUV2 = false;
  40736. _this.UV1 = false;
  40737. _this.UV2 = false;
  40738. _this.ALBEDO = false;
  40739. _this.ALBEDODIRECTUV = 0;
  40740. _this.VERTEXCOLOR = false;
  40741. _this.AMBIENT = false;
  40742. _this.AMBIENTDIRECTUV = 0;
  40743. _this.AMBIENTINGRAYSCALE = false;
  40744. _this.OPACITY = false;
  40745. _this.VERTEXALPHA = false;
  40746. _this.OPACITYDIRECTUV = 0;
  40747. _this.OPACITYRGB = false;
  40748. _this.ALPHATEST = false;
  40749. _this.DEPTHPREPASS = false;
  40750. _this.ALPHABLEND = false;
  40751. _this.ALPHAFROMALBEDO = false;
  40752. _this.ALPHATESTVALUE = 0.5;
  40753. _this.SPECULAROVERALPHA = false;
  40754. _this.RADIANCEOVERALPHA = false;
  40755. _this.ALPHAFRESNEL = false;
  40756. _this.LINEARALPHAFRESNEL = false;
  40757. _this.PREMULTIPLYALPHA = false;
  40758. _this.EMISSIVE = false;
  40759. _this.EMISSIVEDIRECTUV = 0;
  40760. _this.REFLECTIVITY = false;
  40761. _this.REFLECTIVITYDIRECTUV = 0;
  40762. _this.SPECULARTERM = false;
  40763. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40764. _this.MICROSURFACEAUTOMATIC = false;
  40765. _this.LODBASEDMICROSFURACE = false;
  40766. _this.MICROSURFACEMAP = false;
  40767. _this.MICROSURFACEMAPDIRECTUV = 0;
  40768. _this.METALLICWORKFLOW = false;
  40769. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40770. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40771. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40772. _this.AOSTOREINMETALMAPRED = false;
  40773. _this.ENVIRONMENTBRDF = false;
  40774. _this.NORMAL = false;
  40775. _this.TANGENT = false;
  40776. _this.BUMP = false;
  40777. _this.BUMPDIRECTUV = 0;
  40778. _this.OBJECTSPACE_NORMALMAP = false;
  40779. _this.PARALLAX = false;
  40780. _this.PARALLAXOCCLUSION = false;
  40781. _this.NORMALXYSCALE = true;
  40782. _this.LIGHTMAP = false;
  40783. _this.LIGHTMAPDIRECTUV = 0;
  40784. _this.USELIGHTMAPASSHADOWMAP = false;
  40785. _this.GAMMALIGHTMAP = false;
  40786. _this.REFLECTION = false;
  40787. _this.REFLECTIONMAP_3D = false;
  40788. _this.REFLECTIONMAP_SPHERICAL = false;
  40789. _this.REFLECTIONMAP_PLANAR = false;
  40790. _this.REFLECTIONMAP_CUBIC = false;
  40791. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40792. _this.REFLECTIONMAP_PROJECTION = false;
  40793. _this.REFLECTIONMAP_SKYBOX = false;
  40794. _this.REFLECTIONMAP_EXPLICIT = false;
  40795. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40796. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40797. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40798. _this.INVERTCUBICMAP = false;
  40799. _this.USESPHERICALFROMREFLECTIONMAP = false;
  40800. _this.USESPHERICALINVERTEX = false;
  40801. _this.REFLECTIONMAP_OPPOSITEZ = false;
  40802. _this.LODINREFLECTIONALPHA = false;
  40803. _this.GAMMAREFLECTION = false;
  40804. _this.RADIANCEOCCLUSION = false;
  40805. _this.HORIZONOCCLUSION = false;
  40806. _this.REFRACTION = false;
  40807. _this.REFRACTIONMAP_3D = false;
  40808. _this.REFRACTIONMAP_OPPOSITEZ = false;
  40809. _this.LODINREFRACTIONALPHA = false;
  40810. _this.GAMMAREFRACTION = false;
  40811. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  40812. _this.INSTANCES = false;
  40813. _this.NUM_BONE_INFLUENCERS = 0;
  40814. _this.BonesPerMesh = 0;
  40815. _this.NONUNIFORMSCALING = false;
  40816. _this.MORPHTARGETS = false;
  40817. _this.MORPHTARGETS_NORMAL = false;
  40818. _this.MORPHTARGETS_TANGENT = false;
  40819. _this.NUM_MORPH_INFLUENCERS = 0;
  40820. _this.IMAGEPROCESSING = false;
  40821. _this.VIGNETTE = false;
  40822. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  40823. _this.VIGNETTEBLENDMODEOPAQUE = false;
  40824. _this.TONEMAPPING = false;
  40825. _this.CONTRAST = false;
  40826. _this.COLORCURVES = false;
  40827. _this.COLORGRADING = false;
  40828. _this.COLORGRADING3D = false;
  40829. _this.SAMPLER3DGREENDEPTH = false;
  40830. _this.SAMPLER3DBGRMAP = false;
  40831. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  40832. _this.EXPOSURE = false;
  40833. _this.GRAIN = false;
  40834. _this.USEPHYSICALLIGHTFALLOFF = false;
  40835. _this.TWOSIDEDLIGHTING = false;
  40836. _this.SHADOWFLOAT = false;
  40837. _this.CLIPPLANE = false;
  40838. _this.POINTSIZE = false;
  40839. _this.FOG = false;
  40840. _this.LOGARITHMICDEPTH = false;
  40841. _this.FORCENORMALFORWARD = false;
  40842. _this.rebuild();
  40843. return _this;
  40844. }
  40845. /**
  40846. * Resets the PBR Material defines.
  40847. */
  40848. PBRMaterialDefines.prototype.reset = function () {
  40849. _super.prototype.reset.call(this);
  40850. this.ALPHATESTVALUE = 0.5;
  40851. this.PBR = true;
  40852. };
  40853. return PBRMaterialDefines;
  40854. }(BABYLON.MaterialDefines));
  40855. /**
  40856. * The Physically based material base class of BJS.
  40857. *
  40858. * This offers the main features of a standard PBR material.
  40859. * For more information, please refer to the documentation :
  40860. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  40861. */
  40862. var PBRBaseMaterial = /** @class */ (function (_super) {
  40863. __extends(PBRBaseMaterial, _super);
  40864. /**
  40865. * Instantiates a new PBRMaterial instance.
  40866. *
  40867. * @param name The material name
  40868. * @param scene The scene the material will be use in.
  40869. */
  40870. function PBRBaseMaterial(name, scene) {
  40871. var _this = _super.call(this, name, scene) || this;
  40872. /**
  40873. * Intensity of the direct lights e.g. the four lights available in your scene.
  40874. * This impacts both the direct diffuse and specular highlights.
  40875. */
  40876. _this._directIntensity = 1.0;
  40877. /**
  40878. * Intensity of the emissive part of the material.
  40879. * This helps controlling the emissive effect without modifying the emissive color.
  40880. */
  40881. _this._emissiveIntensity = 1.0;
  40882. /**
  40883. * Intensity of the environment e.g. how much the environment will light the object
  40884. * either through harmonics for rough material or through the refelction for shiny ones.
  40885. */
  40886. _this._environmentIntensity = 1.0;
  40887. /**
  40888. * This is a special control allowing the reduction of the specular highlights coming from the
  40889. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  40890. */
  40891. _this._specularIntensity = 1.0;
  40892. /**
  40893. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  40894. */
  40895. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  40896. /**
  40897. * Debug Control allowing disabling the bump map on this material.
  40898. */
  40899. _this._disableBumpMap = false;
  40900. /**
  40901. * AKA Occlusion Texture Intensity in other nomenclature.
  40902. */
  40903. _this._ambientTextureStrength = 1.0;
  40904. /**
  40905. * The color of a material in ambient lighting.
  40906. */
  40907. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  40908. /**
  40909. * AKA Diffuse Color in other nomenclature.
  40910. */
  40911. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  40912. /**
  40913. * AKA Specular Color in other nomenclature.
  40914. */
  40915. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  40916. /**
  40917. * The color applied when light is reflected from a material.
  40918. */
  40919. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  40920. /**
  40921. * The color applied when light is emitted from a material.
  40922. */
  40923. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  40924. /**
  40925. * AKA Glossiness in other nomenclature.
  40926. */
  40927. _this._microSurface = 0.9;
  40928. /**
  40929. * source material index of refraction (IOR)' / 'destination material IOR.
  40930. */
  40931. _this._indexOfRefraction = 0.66;
  40932. /**
  40933. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  40934. */
  40935. _this._invertRefractionY = false;
  40936. /**
  40937. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  40938. * Materials half opaque for instance using refraction could benefit from this control.
  40939. */
  40940. _this._linkRefractionWithTransparency = false;
  40941. /**
  40942. * Specifies that the material will use the light map as a show map.
  40943. */
  40944. _this._useLightmapAsShadowmap = false;
  40945. /**
  40946. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  40947. * makes the reflect vector face the model (under horizon).
  40948. */
  40949. _this._useHorizonOcclusion = true;
  40950. /**
  40951. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  40952. * too much the area relying on ambient texture to define their ambient occlusion.
  40953. */
  40954. _this._useRadianceOcclusion = true;
  40955. /**
  40956. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  40957. */
  40958. _this._useAlphaFromAlbedoTexture = false;
  40959. /**
  40960. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  40961. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  40962. */
  40963. _this._useSpecularOverAlpha = true;
  40964. /**
  40965. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  40966. */
  40967. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  40968. /**
  40969. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  40970. */
  40971. _this._useRoughnessFromMetallicTextureAlpha = true;
  40972. /**
  40973. * Specifies if the metallic texture contains the roughness information in its green channel.
  40974. */
  40975. _this._useRoughnessFromMetallicTextureGreen = false;
  40976. /**
  40977. * Specifies if the metallic texture contains the metallness information in its blue channel.
  40978. */
  40979. _this._useMetallnessFromMetallicTextureBlue = false;
  40980. /**
  40981. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  40982. */
  40983. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  40984. /**
  40985. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  40986. */
  40987. _this._useAmbientInGrayScale = false;
  40988. /**
  40989. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  40990. * The material will try to infer what glossiness each pixel should be.
  40991. */
  40992. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  40993. /**
  40994. * BJS is using an harcoded light falloff based on a manually sets up range.
  40995. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  40996. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  40997. */
  40998. _this._usePhysicalLightFalloff = true;
  40999. /**
  41000. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41001. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41002. */
  41003. _this._useRadianceOverAlpha = true;
  41004. /**
  41005. * Allows using an object space normal map (instead of tangent space).
  41006. */
  41007. _this._useObjectSpaceNormalMap = false;
  41008. /**
  41009. * Allows using the bump map in parallax mode.
  41010. */
  41011. _this._useParallax = false;
  41012. /**
  41013. * Allows using the bump map in parallax occlusion mode.
  41014. */
  41015. _this._useParallaxOcclusion = false;
  41016. /**
  41017. * Controls the scale bias of the parallax mode.
  41018. */
  41019. _this._parallaxScaleBias = 0.05;
  41020. /**
  41021. * If sets to true, disables all the lights affecting the material.
  41022. */
  41023. _this._disableLighting = false;
  41024. /**
  41025. * Number of Simultaneous lights allowed on the material.
  41026. */
  41027. _this._maxSimultaneousLights = 4;
  41028. /**
  41029. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  41030. */
  41031. _this._invertNormalMapX = false;
  41032. /**
  41033. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  41034. */
  41035. _this._invertNormalMapY = false;
  41036. /**
  41037. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41038. */
  41039. _this._twoSidedLighting = false;
  41040. /**
  41041. * Defines the alpha limits in alpha test mode.
  41042. */
  41043. _this._alphaCutOff = 0.4;
  41044. /**
  41045. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41046. */
  41047. _this._forceAlphaTest = false;
  41048. /**
  41049. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41050. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41051. */
  41052. _this._useAlphaFresnel = false;
  41053. /**
  41054. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41055. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41056. */
  41057. _this._useLinearAlphaFresnel = false;
  41058. /**
  41059. * The transparency mode of the material.
  41060. */
  41061. _this._transparencyMode = null;
  41062. /**
  41063. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  41064. * from cos thetav and roughness:
  41065. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  41066. */
  41067. _this._environmentBRDFTexture = null;
  41068. /**
  41069. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41070. */
  41071. _this._forceIrradianceInFragment = false;
  41072. /**
  41073. * Force normal to face away from face.
  41074. */
  41075. _this._forceNormalForward = false;
  41076. /**
  41077. * Stores the available render targets.
  41078. */
  41079. _this._renderTargets = new BABYLON.SmartArray(16);
  41080. /**
  41081. * Sets the global ambient color for the material used in lighting calculations.
  41082. */
  41083. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41084. // Setup the default processing configuration to the scene.
  41085. _this._attachImageProcessingConfiguration(null);
  41086. _this.getRenderTargetTextures = function () {
  41087. _this._renderTargets.reset();
  41088. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41089. _this._renderTargets.push(_this._reflectionTexture);
  41090. }
  41091. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41092. _this._renderTargets.push(_this._refractionTexture);
  41093. }
  41094. return _this._renderTargets;
  41095. };
  41096. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41097. return _this;
  41098. }
  41099. /**
  41100. * Attaches a new image processing configuration to the PBR Material.
  41101. * @param configuration
  41102. */
  41103. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41104. var _this = this;
  41105. if (configuration === this._imageProcessingConfiguration) {
  41106. return;
  41107. }
  41108. // Detaches observer.
  41109. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41110. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41111. }
  41112. // Pick the scene configuration if needed.
  41113. if (!configuration) {
  41114. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41115. }
  41116. else {
  41117. this._imageProcessingConfiguration = configuration;
  41118. }
  41119. // Attaches observer.
  41120. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41121. _this._markAllSubMeshesAsImageProcessingDirty();
  41122. });
  41123. };
  41124. /**
  41125. * Gets the name of the material class.
  41126. */
  41127. PBRBaseMaterial.prototype.getClassName = function () {
  41128. return "PBRBaseMaterial";
  41129. };
  41130. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  41131. /**
  41132. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  41133. */
  41134. get: function () {
  41135. return this._useLogarithmicDepth;
  41136. },
  41137. /**
  41138. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  41139. */
  41140. set: function (value) {
  41141. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41142. },
  41143. enumerable: true,
  41144. configurable: true
  41145. });
  41146. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  41147. /**
  41148. * Gets the current transparency mode.
  41149. */
  41150. get: function () {
  41151. return this._transparencyMode;
  41152. },
  41153. /**
  41154. * Sets the transparency mode of the material.
  41155. */
  41156. set: function (value) {
  41157. if (this._transparencyMode === value) {
  41158. return;
  41159. }
  41160. this._transparencyMode = value;
  41161. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  41162. this._markAllSubMeshesAsTexturesAndMiscDirty();
  41163. },
  41164. enumerable: true,
  41165. configurable: true
  41166. });
  41167. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  41168. /**
  41169. * Returns true if alpha blending should be disabled.
  41170. */
  41171. get: function () {
  41172. return (this._linkRefractionWithTransparency ||
  41173. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  41174. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41175. },
  41176. enumerable: true,
  41177. configurable: true
  41178. });
  41179. /**
  41180. * Specifies whether or not this material should be rendered in alpha blend mode.
  41181. */
  41182. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  41183. if (this._disableAlphaBlending) {
  41184. return false;
  41185. }
  41186. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  41187. };
  41188. /**
  41189. * Specifies if the mesh will require alpha blending.
  41190. * @param mesh - BJS mesh.
  41191. */
  41192. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  41193. if (this._disableAlphaBlending) {
  41194. return false;
  41195. }
  41196. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  41197. };
  41198. /**
  41199. * Specifies whether or not this material should be rendered in alpha test mode.
  41200. */
  41201. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  41202. if (this._forceAlphaTest) {
  41203. return true;
  41204. }
  41205. if (this._linkRefractionWithTransparency) {
  41206. return false;
  41207. }
  41208. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41209. };
  41210. /**
  41211. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  41212. */
  41213. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  41214. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  41215. };
  41216. /**
  41217. * Gets the texture used for the alpha test.
  41218. */
  41219. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  41220. return this._albedoTexture;
  41221. };
  41222. /**
  41223. * Specifies that the submesh is ready to be used.
  41224. * @param mesh - BJS mesh.
  41225. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  41226. * @param useInstances - Specifies that instances should be used.
  41227. * @returns - boolean indicating that the submesh is ready or not.
  41228. */
  41229. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41230. if (subMesh.effect && this.isFrozen) {
  41231. if (this._wasPreviouslyReady) {
  41232. return true;
  41233. }
  41234. }
  41235. if (!subMesh._materialDefines) {
  41236. subMesh._materialDefines = new PBRMaterialDefines();
  41237. }
  41238. var defines = subMesh._materialDefines;
  41239. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41240. if (defines._renderId === this.getScene().getRenderId()) {
  41241. return true;
  41242. }
  41243. }
  41244. var scene = this.getScene();
  41245. var engine = scene.getEngine();
  41246. if (defines._areTexturesDirty) {
  41247. if (scene.texturesEnabled) {
  41248. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41249. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  41250. return false;
  41251. }
  41252. }
  41253. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41254. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41255. return false;
  41256. }
  41257. }
  41258. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41259. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41260. return false;
  41261. }
  41262. }
  41263. var reflectionTexture = this._getReflectionTexture();
  41264. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41265. if (!reflectionTexture.isReadyOrNotBlocking()) {
  41266. return false;
  41267. }
  41268. }
  41269. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41270. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41271. return false;
  41272. }
  41273. }
  41274. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41275. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41276. return false;
  41277. }
  41278. }
  41279. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41280. if (this._metallicTexture) {
  41281. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  41282. return false;
  41283. }
  41284. }
  41285. else if (this._reflectivityTexture) {
  41286. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  41287. return false;
  41288. }
  41289. }
  41290. if (this._microSurfaceTexture) {
  41291. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  41292. return false;
  41293. }
  41294. }
  41295. }
  41296. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41297. // Bump texture cannot be not blocking.
  41298. if (!this._bumpTexture.isReady()) {
  41299. return false;
  41300. }
  41301. }
  41302. var refractionTexture = this._getRefractionTexture();
  41303. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41304. if (!refractionTexture.isReadyOrNotBlocking()) {
  41305. return false;
  41306. }
  41307. }
  41308. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41309. // This is blocking.
  41310. if (!this._environmentBRDFTexture.isReady()) {
  41311. return false;
  41312. }
  41313. }
  41314. }
  41315. }
  41316. if (defines._areImageProcessingDirty) {
  41317. if (!this._imageProcessingConfiguration.isReady()) {
  41318. return false;
  41319. }
  41320. }
  41321. if (!engine.getCaps().standardDerivatives) {
  41322. var bufferMesh = null;
  41323. if (mesh.getClassName() === "InstancedMesh") {
  41324. bufferMesh = mesh.sourceMesh;
  41325. }
  41326. else if (mesh.getClassName() === "Mesh") {
  41327. bufferMesh = mesh;
  41328. }
  41329. if (bufferMesh && bufferMesh.geometry && bufferMesh.geometry.isReady() && !bufferMesh.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41330. bufferMesh.createNormals(true);
  41331. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  41332. }
  41333. }
  41334. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  41335. if (effect) {
  41336. scene.resetCachedMaterial();
  41337. subMesh.setEffect(effect, defines);
  41338. this.buildUniformLayout();
  41339. }
  41340. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41341. return false;
  41342. }
  41343. defines._renderId = scene.getRenderId();
  41344. this._wasPreviouslyReady = true;
  41345. return true;
  41346. };
  41347. /**
  41348. * Specifies if the material uses metallic roughness workflow.
  41349. * @returns boolean specifiying if the material uses metallic roughness workflow.
  41350. */
  41351. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  41352. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  41353. return true;
  41354. }
  41355. return false;
  41356. };
  41357. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  41358. if (onCompiled === void 0) { onCompiled = null; }
  41359. if (onError === void 0) { onError = null; }
  41360. if (useInstances === void 0) { useInstances = null; }
  41361. if (useClipPlane === void 0) { useClipPlane = null; }
  41362. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  41363. if (!defines.isDirty) {
  41364. return null;
  41365. }
  41366. defines.markAsProcessed();
  41367. var scene = this.getScene();
  41368. var engine = scene.getEngine();
  41369. // Fallbacks
  41370. var fallbacks = new BABYLON.EffectFallbacks();
  41371. var fallbackRank = 0;
  41372. if (defines.USESPHERICALINVERTEX) {
  41373. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  41374. }
  41375. if (defines.FOG) {
  41376. fallbacks.addFallback(fallbackRank, "FOG");
  41377. }
  41378. if (defines.POINTSIZE) {
  41379. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  41380. }
  41381. if (defines.LOGARITHMICDEPTH) {
  41382. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  41383. }
  41384. if (defines.PARALLAX) {
  41385. fallbacks.addFallback(fallbackRank, "PARALLAX");
  41386. }
  41387. if (defines.PARALLAXOCCLUSION) {
  41388. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  41389. }
  41390. if (defines.ENVIRONMENTBRDF) {
  41391. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  41392. }
  41393. if (defines.TANGENT) {
  41394. fallbacks.addFallback(fallbackRank++, "TANGENT");
  41395. }
  41396. if (defines.BUMP) {
  41397. fallbacks.addFallback(fallbackRank++, "BUMP");
  41398. }
  41399. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  41400. if (defines.SPECULARTERM) {
  41401. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  41402. }
  41403. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  41404. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  41405. }
  41406. if (defines.LIGHTMAP) {
  41407. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  41408. }
  41409. if (defines.NORMAL) {
  41410. fallbacks.addFallback(fallbackRank++, "NORMAL");
  41411. }
  41412. if (defines.AMBIENT) {
  41413. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  41414. }
  41415. if (defines.EMISSIVE) {
  41416. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  41417. }
  41418. if (defines.VERTEXCOLOR) {
  41419. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  41420. }
  41421. if (defines.NUM_BONE_INFLUENCERS > 0) {
  41422. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  41423. }
  41424. if (defines.MORPHTARGETS) {
  41425. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  41426. }
  41427. //Attributes
  41428. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41429. if (defines.NORMAL) {
  41430. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41431. }
  41432. if (defines.TANGENT) {
  41433. attribs.push(BABYLON.VertexBuffer.TangentKind);
  41434. }
  41435. if (defines.UV1) {
  41436. attribs.push(BABYLON.VertexBuffer.UVKind);
  41437. }
  41438. if (defines.UV2) {
  41439. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41440. }
  41441. if (defines.VERTEXCOLOR) {
  41442. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41443. }
  41444. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41445. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41446. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41447. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  41448. "vFogInfos", "vFogColor", "pointSize",
  41449. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  41450. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41451. "mBones",
  41452. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  41453. "vLightingIntensity",
  41454. "logarithmicDepthConstant",
  41455. "vSphericalX", "vSphericalY", "vSphericalZ",
  41456. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  41457. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  41458. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  41459. "vTangentSpaceParams"
  41460. ];
  41461. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  41462. "bumpSampler", "lightmapSampler", "opacitySampler",
  41463. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  41464. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  41465. "microSurfaceSampler", "environmentBrdfSampler"];
  41466. var uniformBuffers = ["Material", "Scene"];
  41467. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41468. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41469. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41470. uniformsNames: uniforms,
  41471. uniformBuffersNames: uniformBuffers,
  41472. samplers: samplers,
  41473. defines: defines,
  41474. maxSimultaneousLights: this._maxSimultaneousLights
  41475. });
  41476. var join = defines.toString();
  41477. return engine.createEffect("pbr", {
  41478. attributes: attribs,
  41479. uniformsNames: uniforms,
  41480. uniformBuffersNames: uniformBuffers,
  41481. samplers: samplers,
  41482. defines: join,
  41483. fallbacks: fallbacks,
  41484. onCompiled: onCompiled,
  41485. onError: onError,
  41486. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41487. }, engine);
  41488. };
  41489. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  41490. if (useInstances === void 0) { useInstances = null; }
  41491. if (useClipPlane === void 0) { useClipPlane = null; }
  41492. var scene = this.getScene();
  41493. var engine = scene.getEngine();
  41494. // Lights
  41495. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41496. defines._needNormals = true;
  41497. // Textures
  41498. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  41499. if (defines._areTexturesDirty) {
  41500. defines._needUVs = false;
  41501. if (scene.texturesEnabled) {
  41502. if (scene.getEngine().getCaps().textureLOD) {
  41503. defines.LODBASEDMICROSFURACE = true;
  41504. }
  41505. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41506. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  41507. }
  41508. else {
  41509. defines.ALBEDO = false;
  41510. }
  41511. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41512. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41513. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  41514. }
  41515. else {
  41516. defines.AMBIENT = false;
  41517. }
  41518. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41519. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41520. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41521. }
  41522. else {
  41523. defines.OPACITY = false;
  41524. }
  41525. var reflectionTexture = this._getReflectionTexture();
  41526. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41527. defines.REFLECTION = true;
  41528. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  41529. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  41530. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  41531. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  41532. defines.INVERTCUBICMAP = true;
  41533. }
  41534. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  41535. switch (reflectionTexture.coordinatesMode) {
  41536. case BABYLON.Texture.CUBIC_MODE:
  41537. case BABYLON.Texture.INVCUBIC_MODE:
  41538. defines.REFLECTIONMAP_CUBIC = true;
  41539. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  41540. break;
  41541. case BABYLON.Texture.EXPLICIT_MODE:
  41542. defines.REFLECTIONMAP_EXPLICIT = true;
  41543. break;
  41544. case BABYLON.Texture.PLANAR_MODE:
  41545. defines.REFLECTIONMAP_PLANAR = true;
  41546. break;
  41547. case BABYLON.Texture.PROJECTION_MODE:
  41548. defines.REFLECTIONMAP_PROJECTION = true;
  41549. break;
  41550. case BABYLON.Texture.SKYBOX_MODE:
  41551. defines.REFLECTIONMAP_SKYBOX = true;
  41552. break;
  41553. case BABYLON.Texture.SPHERICAL_MODE:
  41554. defines.REFLECTIONMAP_SPHERICAL = true;
  41555. break;
  41556. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41557. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  41558. break;
  41559. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41560. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  41561. break;
  41562. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41563. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  41564. break;
  41565. }
  41566. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  41567. if (reflectionTexture.sphericalPolynomial) {
  41568. defines.USESPHERICALFROMREFLECTIONMAP = true;
  41569. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  41570. defines.USESPHERICALINVERTEX = false;
  41571. }
  41572. else {
  41573. defines.USESPHERICALINVERTEX = true;
  41574. }
  41575. }
  41576. }
  41577. }
  41578. else {
  41579. defines.REFLECTION = false;
  41580. defines.REFLECTIONMAP_3D = false;
  41581. defines.REFLECTIONMAP_SPHERICAL = false;
  41582. defines.REFLECTIONMAP_PLANAR = false;
  41583. defines.REFLECTIONMAP_CUBIC = false;
  41584. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41585. defines.REFLECTIONMAP_PROJECTION = false;
  41586. defines.REFLECTIONMAP_SKYBOX = false;
  41587. defines.REFLECTIONMAP_EXPLICIT = false;
  41588. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41589. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41590. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41591. defines.INVERTCUBICMAP = false;
  41592. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41593. defines.USESPHERICALINVERTEX = false;
  41594. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41595. defines.LODINREFLECTIONALPHA = false;
  41596. defines.GAMMAREFLECTION = false;
  41597. }
  41598. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41599. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41600. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41601. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  41602. }
  41603. else {
  41604. defines.LIGHTMAP = false;
  41605. }
  41606. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41607. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41608. }
  41609. else {
  41610. defines.EMISSIVE = false;
  41611. }
  41612. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41613. if (this._metallicTexture) {
  41614. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41615. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41616. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41617. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41618. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41619. }
  41620. else if (this._reflectivityTexture) {
  41621. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41622. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41623. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41624. }
  41625. else {
  41626. defines.REFLECTIVITY = false;
  41627. }
  41628. if (this._microSurfaceTexture) {
  41629. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41630. }
  41631. else {
  41632. defines.MICROSURFACEMAP = false;
  41633. }
  41634. }
  41635. else {
  41636. defines.REFLECTIVITY = false;
  41637. defines.MICROSURFACEMAP = false;
  41638. }
  41639. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41640. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41641. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41642. defines.PARALLAX = true;
  41643. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41644. }
  41645. else {
  41646. defines.PARALLAX = false;
  41647. }
  41648. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41649. }
  41650. else {
  41651. defines.BUMP = false;
  41652. }
  41653. var refractionTexture = this._getRefractionTexture();
  41654. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41655. defines.REFRACTION = true;
  41656. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41657. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41658. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41659. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41660. if (this._linkRefractionWithTransparency) {
  41661. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41662. }
  41663. }
  41664. else {
  41665. defines.REFRACTION = false;
  41666. }
  41667. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41668. defines.ENVIRONMENTBRDF = true;
  41669. }
  41670. else {
  41671. defines.ENVIRONMENTBRDF = false;
  41672. }
  41673. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41674. defines.ALPHAFROMALBEDO = true;
  41675. }
  41676. else {
  41677. defines.ALPHAFROMALBEDO = false;
  41678. }
  41679. }
  41680. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41681. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41682. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41683. if (!this.backFaceCulling && this._twoSidedLighting) {
  41684. defines.TWOSIDEDLIGHTING = true;
  41685. }
  41686. else {
  41687. defines.TWOSIDEDLIGHTING = false;
  41688. }
  41689. defines.ALPHATESTVALUE = this._alphaCutOff;
  41690. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41691. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41692. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41693. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41694. }
  41695. if (defines._areImageProcessingDirty) {
  41696. this._imageProcessingConfiguration.prepareDefines(defines);
  41697. }
  41698. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41699. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41700. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41701. // Misc.
  41702. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41703. // Values that need to be evaluated on every frame
  41704. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41705. // Attribs
  41706. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41707. };
  41708. /**
  41709. * Force shader compilation
  41710. */
  41711. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41712. var _this = this;
  41713. var localOptions = __assign({ clipPlane: false }, options);
  41714. var defines = new PBRMaterialDefines();
  41715. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41716. if (effect.isReady()) {
  41717. if (onCompiled) {
  41718. onCompiled(this);
  41719. }
  41720. }
  41721. else {
  41722. effect.onCompileObservable.add(function () {
  41723. if (onCompiled) {
  41724. onCompiled(_this);
  41725. }
  41726. });
  41727. }
  41728. };
  41729. /**
  41730. * Initializes the uniform buffer layout for the shader.
  41731. */
  41732. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41733. // Order is important !
  41734. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41735. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41736. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41737. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41738. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41739. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41740. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41741. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41742. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41743. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41744. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41745. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41746. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41747. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41748. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41749. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41750. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41751. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41752. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41753. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41754. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41755. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41756. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41757. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41758. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41759. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41760. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41761. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41762. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41763. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41764. this._uniformBuffer.addUniform("pointSize", 1);
  41765. this._uniformBuffer.create();
  41766. };
  41767. /**
  41768. * Unbinds the textures.
  41769. */
  41770. PBRBaseMaterial.prototype.unbind = function () {
  41771. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41772. this._uniformBuffer.setTexture("reflectionSampler", null);
  41773. }
  41774. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41775. this._uniformBuffer.setTexture("refractionSampler", null);
  41776. }
  41777. _super.prototype.unbind.call(this);
  41778. };
  41779. /**
  41780. * Binds the submesh data.
  41781. * @param world - The world matrix.
  41782. * @param mesh - The BJS mesh.
  41783. * @param subMesh - A submesh of the BJS mesh.
  41784. */
  41785. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41786. var scene = this.getScene();
  41787. var defines = subMesh._materialDefines;
  41788. if (!defines) {
  41789. return;
  41790. }
  41791. var effect = subMesh.effect;
  41792. if (!effect) {
  41793. return;
  41794. }
  41795. this._activeEffect = effect;
  41796. // Matrices
  41797. this.bindOnlyWorldMatrix(world);
  41798. // Normal Matrix
  41799. if (defines.OBJECTSPACE_NORMALMAP) {
  41800. world.toNormalMatrix(this._normalMatrix);
  41801. this.bindOnlyNormalMatrix(this._normalMatrix);
  41802. }
  41803. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41804. // Bones
  41805. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  41806. var reflectionTexture = null;
  41807. if (mustRebind) {
  41808. this._uniformBuffer.bindToEffect(effect, "Material");
  41809. this.bindViewProjection(effect);
  41810. reflectionTexture = this._getReflectionTexture();
  41811. var refractionTexture = this._getRefractionTexture();
  41812. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41813. // Texture uniforms
  41814. if (scene.texturesEnabled) {
  41815. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41816. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  41817. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  41818. }
  41819. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41820. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  41821. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41822. }
  41823. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41824. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41825. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41826. }
  41827. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41828. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  41829. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  41830. if (reflectionTexture.boundingBoxSize) {
  41831. var cubeTexture = reflectionTexture;
  41832. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41833. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41834. }
  41835. var polynomials = reflectionTexture.sphericalPolynomial;
  41836. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  41837. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  41838. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  41839. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  41840. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  41841. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  41842. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  41843. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  41844. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  41845. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  41846. }
  41847. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  41848. }
  41849. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41850. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  41851. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  41852. }
  41853. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41854. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  41855. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  41856. }
  41857. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41858. if (this._metallicTexture) {
  41859. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  41860. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  41861. }
  41862. else if (this._reflectivityTexture) {
  41863. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  41864. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  41865. }
  41866. if (this._microSurfaceTexture) {
  41867. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  41868. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  41869. }
  41870. }
  41871. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41872. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  41873. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  41874. if (scene._mirroredCameraPosition) {
  41875. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  41876. }
  41877. else {
  41878. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  41879. }
  41880. }
  41881. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41882. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  41883. var depth = 1.0;
  41884. if (!refractionTexture.isCube) {
  41885. if (refractionTexture.depth) {
  41886. depth = refractionTexture.depth;
  41887. }
  41888. }
  41889. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  41890. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  41891. }
  41892. }
  41893. // Point size
  41894. if (this.pointsCloud) {
  41895. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  41896. }
  41897. // Colors
  41898. if (defines.METALLICWORKFLOW) {
  41899. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  41900. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  41901. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  41902. }
  41903. else {
  41904. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  41905. }
  41906. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  41907. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  41908. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  41909. // Misc
  41910. this._lightingInfos.x = this._directIntensity;
  41911. this._lightingInfos.y = this._emissiveIntensity;
  41912. this._lightingInfos.z = this._environmentIntensity;
  41913. this._lightingInfos.w = this._specularIntensity;
  41914. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  41915. }
  41916. // Textures
  41917. if (scene.texturesEnabled) {
  41918. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41919. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  41920. }
  41921. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41922. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  41923. }
  41924. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41925. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  41926. }
  41927. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41928. if (defines.LODBASEDMICROSFURACE) {
  41929. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  41930. }
  41931. else {
  41932. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  41933. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  41934. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  41935. }
  41936. }
  41937. if (defines.ENVIRONMENTBRDF) {
  41938. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  41939. }
  41940. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41941. if (defines.LODBASEDMICROSFURACE) {
  41942. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  41943. }
  41944. else {
  41945. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  41946. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  41947. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  41948. }
  41949. }
  41950. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41951. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  41952. }
  41953. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41954. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  41955. }
  41956. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41957. if (this._metallicTexture) {
  41958. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  41959. }
  41960. else if (this._reflectivityTexture) {
  41961. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  41962. }
  41963. if (this._microSurfaceTexture) {
  41964. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  41965. }
  41966. }
  41967. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41968. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  41969. }
  41970. }
  41971. // Clip plane
  41972. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  41973. // Colors
  41974. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  41975. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41976. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  41977. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  41978. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  41979. }
  41980. if (mustRebind || !this.isFrozen) {
  41981. // Lights
  41982. if (scene.lightsEnabled && !this._disableLighting) {
  41983. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  41984. }
  41985. // View
  41986. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  41987. this.bindView(effect);
  41988. }
  41989. // Fog
  41990. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  41991. // Morph targets
  41992. if (defines.NUM_MORPH_INFLUENCERS) {
  41993. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  41994. }
  41995. // image processing
  41996. this._imageProcessingConfiguration.bind(this._activeEffect);
  41997. // Log. depth
  41998. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  41999. }
  42000. this._uniformBuffer.update();
  42001. this._afterBind(mesh);
  42002. };
  42003. /**
  42004. * Returns the animatable textures.
  42005. * @returns - Array of animatable textures.
  42006. */
  42007. PBRBaseMaterial.prototype.getAnimatables = function () {
  42008. var results = [];
  42009. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  42010. results.push(this._albedoTexture);
  42011. }
  42012. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42013. results.push(this._ambientTexture);
  42014. }
  42015. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42016. results.push(this._opacityTexture);
  42017. }
  42018. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42019. results.push(this._reflectionTexture);
  42020. }
  42021. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42022. results.push(this._emissiveTexture);
  42023. }
  42024. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  42025. results.push(this._metallicTexture);
  42026. }
  42027. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  42028. results.push(this._reflectivityTexture);
  42029. }
  42030. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42031. results.push(this._bumpTexture);
  42032. }
  42033. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42034. results.push(this._lightmapTexture);
  42035. }
  42036. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42037. results.push(this._refractionTexture);
  42038. }
  42039. return results;
  42040. };
  42041. /**
  42042. * Returns the texture used for reflections.
  42043. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  42044. */
  42045. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  42046. if (this._reflectionTexture) {
  42047. return this._reflectionTexture;
  42048. }
  42049. return this.getScene().environmentTexture;
  42050. };
  42051. /**
  42052. * Returns the texture used for refraction or null if none is used.
  42053. * @returns - Refection texture if present. If no refraction texture and refraction
  42054. * is linked with transparency, returns environment texture. Otherwise, returns null.
  42055. */
  42056. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  42057. if (this._refractionTexture) {
  42058. return this._refractionTexture;
  42059. }
  42060. if (this._linkRefractionWithTransparency) {
  42061. return this.getScene().environmentTexture;
  42062. }
  42063. return null;
  42064. };
  42065. /**
  42066. * Disposes the resources of the material.
  42067. * @param forceDisposeEffect - Forces the disposal of effects.
  42068. * @param forceDisposeTextures - Forces the disposal of all textures.
  42069. */
  42070. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42071. if (forceDisposeTextures) {
  42072. if (this._albedoTexture) {
  42073. this._albedoTexture.dispose();
  42074. }
  42075. if (this._ambientTexture) {
  42076. this._ambientTexture.dispose();
  42077. }
  42078. if (this._opacityTexture) {
  42079. this._opacityTexture.dispose();
  42080. }
  42081. if (this._reflectionTexture) {
  42082. this._reflectionTexture.dispose();
  42083. }
  42084. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  42085. this._environmentBRDFTexture.dispose();
  42086. }
  42087. if (this._emissiveTexture) {
  42088. this._emissiveTexture.dispose();
  42089. }
  42090. if (this._metallicTexture) {
  42091. this._metallicTexture.dispose();
  42092. }
  42093. if (this._reflectivityTexture) {
  42094. this._reflectivityTexture.dispose();
  42095. }
  42096. if (this._bumpTexture) {
  42097. this._bumpTexture.dispose();
  42098. }
  42099. if (this._lightmapTexture) {
  42100. this._lightmapTexture.dispose();
  42101. }
  42102. if (this._refractionTexture) {
  42103. this._refractionTexture.dispose();
  42104. }
  42105. }
  42106. this._renderTargets.dispose();
  42107. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42108. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42109. }
  42110. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42111. };
  42112. /**
  42113. * Stores the reflectivity values based on metallic roughness workflow.
  42114. */
  42115. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  42116. __decorate([
  42117. BABYLON.serializeAsImageProcessingConfiguration()
  42118. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  42119. __decorate([
  42120. BABYLON.serialize()
  42121. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  42122. __decorate([
  42123. BABYLON.serialize()
  42124. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  42125. return PBRBaseMaterial;
  42126. }(BABYLON.PushMaterial));
  42127. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  42128. })(BABYLON || (BABYLON = {}));
  42129. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  42130. var BABYLON;
  42131. (function (BABYLON) {
  42132. /**
  42133. * The Physically based simple base material of BJS.
  42134. *
  42135. * This enables better naming and convention enforcements on top of the pbrMaterial.
  42136. * It is used as the base class for both the specGloss and metalRough conventions.
  42137. */
  42138. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  42139. __extends(PBRBaseSimpleMaterial, _super);
  42140. /**
  42141. * Instantiates a new PBRMaterial instance.
  42142. *
  42143. * @param name The material name
  42144. * @param scene The scene the material will be use in.
  42145. */
  42146. function PBRBaseSimpleMaterial(name, scene) {
  42147. var _this = _super.call(this, name, scene) || this;
  42148. /**
  42149. * Number of Simultaneous lights allowed on the material.
  42150. */
  42151. _this.maxSimultaneousLights = 4;
  42152. /**
  42153. * If sets to true, disables all the lights affecting the material.
  42154. */
  42155. _this.disableLighting = false;
  42156. /**
  42157. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42158. */
  42159. _this.invertNormalMapX = false;
  42160. /**
  42161. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42162. */
  42163. _this.invertNormalMapY = false;
  42164. /**
  42165. * Emissivie color used to self-illuminate the model.
  42166. */
  42167. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42168. /**
  42169. * Occlusion Channel Strenght.
  42170. */
  42171. _this.occlusionStrength = 1.0;
  42172. _this.useLightmapAsShadowmap = false;
  42173. _this._useAlphaFromAlbedoTexture = true;
  42174. _this._useAmbientInGrayScale = true;
  42175. return _this;
  42176. }
  42177. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  42178. /**
  42179. * Gets the current double sided mode.
  42180. */
  42181. get: function () {
  42182. return this._twoSidedLighting;
  42183. },
  42184. /**
  42185. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42186. */
  42187. set: function (value) {
  42188. if (this._twoSidedLighting === value) {
  42189. return;
  42190. }
  42191. this._twoSidedLighting = value;
  42192. this.backFaceCulling = !value;
  42193. this._markAllSubMeshesAsTexturesDirty();
  42194. },
  42195. enumerable: true,
  42196. configurable: true
  42197. });
  42198. /**
  42199. * Return the active textures of the material.
  42200. */
  42201. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  42202. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42203. if (this.environmentTexture) {
  42204. activeTextures.push(this.environmentTexture);
  42205. }
  42206. if (this.normalTexture) {
  42207. activeTextures.push(this.normalTexture);
  42208. }
  42209. if (this.emissiveTexture) {
  42210. activeTextures.push(this.emissiveTexture);
  42211. }
  42212. if (this.occlusionTexture) {
  42213. activeTextures.push(this.occlusionTexture);
  42214. }
  42215. if (this.lightmapTexture) {
  42216. activeTextures.push(this.lightmapTexture);
  42217. }
  42218. return activeTextures;
  42219. };
  42220. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  42221. if (_super.prototype.hasTexture.call(this, texture)) {
  42222. return true;
  42223. }
  42224. if (this.lightmapTexture === texture) {
  42225. return true;
  42226. }
  42227. return false;
  42228. };
  42229. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  42230. return "PBRBaseSimpleMaterial";
  42231. };
  42232. __decorate([
  42233. BABYLON.serialize(),
  42234. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42235. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  42236. __decorate([
  42237. BABYLON.serialize(),
  42238. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42239. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  42240. __decorate([
  42241. BABYLON.serializeAsTexture(),
  42242. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  42243. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  42244. __decorate([
  42245. BABYLON.serialize(),
  42246. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42247. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  42248. __decorate([
  42249. BABYLON.serialize(),
  42250. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42251. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  42252. __decorate([
  42253. BABYLON.serializeAsTexture(),
  42254. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  42255. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  42256. __decorate([
  42257. BABYLON.serializeAsColor3("emissive"),
  42258. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42259. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  42260. __decorate([
  42261. BABYLON.serializeAsTexture(),
  42262. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42263. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  42264. __decorate([
  42265. BABYLON.serialize(),
  42266. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  42267. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  42268. __decorate([
  42269. BABYLON.serializeAsTexture(),
  42270. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  42271. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  42272. __decorate([
  42273. BABYLON.serialize(),
  42274. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  42275. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  42276. __decorate([
  42277. BABYLON.serialize()
  42278. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  42279. __decorate([
  42280. BABYLON.serializeAsTexture(),
  42281. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42282. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  42283. __decorate([
  42284. BABYLON.serialize(),
  42285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42286. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42287. return PBRBaseSimpleMaterial;
  42288. }(BABYLON.PBRBaseMaterial));
  42289. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  42290. })(BABYLON || (BABYLON = {}));
  42291. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  42292. var BABYLON;
  42293. (function (BABYLON) {
  42294. /**
  42295. * The Physically based material of BJS.
  42296. *
  42297. * This offers the main features of a standard PBR material.
  42298. * For more information, please refer to the documentation :
  42299. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  42300. */
  42301. var PBRMaterial = /** @class */ (function (_super) {
  42302. __extends(PBRMaterial, _super);
  42303. /**
  42304. * Instantiates a new PBRMaterial instance.
  42305. *
  42306. * @param name The material name
  42307. * @param scene The scene the material will be use in.
  42308. */
  42309. function PBRMaterial(name, scene) {
  42310. var _this = _super.call(this, name, scene) || this;
  42311. /**
  42312. * Intensity of the direct lights e.g. the four lights available in your scene.
  42313. * This impacts both the direct diffuse and specular highlights.
  42314. */
  42315. _this.directIntensity = 1.0;
  42316. /**
  42317. * Intensity of the emissive part of the material.
  42318. * This helps controlling the emissive effect without modifying the emissive color.
  42319. */
  42320. _this.emissiveIntensity = 1.0;
  42321. /**
  42322. * Intensity of the environment e.g. how much the environment will light the object
  42323. * either through harmonics for rough material or through the refelction for shiny ones.
  42324. */
  42325. _this.environmentIntensity = 1.0;
  42326. /**
  42327. * This is a special control allowing the reduction of the specular highlights coming from the
  42328. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  42329. */
  42330. _this.specularIntensity = 1.0;
  42331. /**
  42332. * Debug Control allowing disabling the bump map on this material.
  42333. */
  42334. _this.disableBumpMap = false;
  42335. /**
  42336. * AKA Occlusion Texture Intensity in other nomenclature.
  42337. */
  42338. _this.ambientTextureStrength = 1.0;
  42339. /**
  42340. * The color of a material in ambient lighting.
  42341. */
  42342. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42343. /**
  42344. * AKA Diffuse Color in other nomenclature.
  42345. */
  42346. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  42347. /**
  42348. * AKA Specular Color in other nomenclature.
  42349. */
  42350. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  42351. /**
  42352. * The color reflected from the material.
  42353. */
  42354. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  42355. /**
  42356. * The color emitted from the material.
  42357. */
  42358. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42359. /**
  42360. * AKA Glossiness in other nomenclature.
  42361. */
  42362. _this.microSurface = 1.0;
  42363. /**
  42364. * source material index of refraction (IOR)' / 'destination material IOR.
  42365. */
  42366. _this.indexOfRefraction = 0.66;
  42367. /**
  42368. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  42369. */
  42370. _this.invertRefractionY = false;
  42371. /**
  42372. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  42373. * Materials half opaque for instance using refraction could benefit from this control.
  42374. */
  42375. _this.linkRefractionWithTransparency = false;
  42376. _this.useLightmapAsShadowmap = false;
  42377. /**
  42378. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  42379. */
  42380. _this.useAlphaFromAlbedoTexture = false;
  42381. /**
  42382. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  42383. */
  42384. _this.forceAlphaTest = false;
  42385. /**
  42386. * Defines the alpha limits in alpha test mode.
  42387. */
  42388. _this.alphaCutOff = 0.4;
  42389. /**
  42390. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  42391. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  42392. */
  42393. _this.useSpecularOverAlpha = true;
  42394. /**
  42395. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  42396. */
  42397. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  42398. /**
  42399. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  42400. */
  42401. _this.useRoughnessFromMetallicTextureAlpha = true;
  42402. /**
  42403. * Specifies if the metallic texture contains the roughness information in its green channel.
  42404. */
  42405. _this.useRoughnessFromMetallicTextureGreen = false;
  42406. /**
  42407. * Specifies if the metallic texture contains the metallness information in its blue channel.
  42408. */
  42409. _this.useMetallnessFromMetallicTextureBlue = false;
  42410. /**
  42411. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  42412. */
  42413. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  42414. /**
  42415. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  42416. */
  42417. _this.useAmbientInGrayScale = false;
  42418. /**
  42419. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  42420. * The material will try to infer what glossiness each pixel should be.
  42421. */
  42422. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  42423. /**
  42424. * BJS is using an harcoded light falloff based on a manually sets up range.
  42425. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  42426. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  42427. */
  42428. _this.usePhysicalLightFalloff = true;
  42429. /**
  42430. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  42431. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  42432. */
  42433. _this.useRadianceOverAlpha = true;
  42434. /**
  42435. * Allows using an object space normal map (instead of tangent space).
  42436. */
  42437. _this.useObjectSpaceNormalMap = false;
  42438. /**
  42439. * Allows using the bump map in parallax mode.
  42440. */
  42441. _this.useParallax = false;
  42442. /**
  42443. * Allows using the bump map in parallax occlusion mode.
  42444. */
  42445. _this.useParallaxOcclusion = false;
  42446. /**
  42447. * Controls the scale bias of the parallax mode.
  42448. */
  42449. _this.parallaxScaleBias = 0.05;
  42450. /**
  42451. * If sets to true, disables all the lights affecting the material.
  42452. */
  42453. _this.disableLighting = false;
  42454. /**
  42455. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  42456. */
  42457. _this.forceIrradianceInFragment = false;
  42458. /**
  42459. * Number of Simultaneous lights allowed on the material.
  42460. */
  42461. _this.maxSimultaneousLights = 4;
  42462. /**
  42463. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42464. */
  42465. _this.invertNormalMapX = false;
  42466. /**
  42467. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42468. */
  42469. _this.invertNormalMapY = false;
  42470. /**
  42471. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42472. */
  42473. _this.twoSidedLighting = false;
  42474. /**
  42475. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42476. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  42477. */
  42478. _this.useAlphaFresnel = false;
  42479. /**
  42480. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42481. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  42482. */
  42483. _this.useLinearAlphaFresnel = false;
  42484. /**
  42485. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42486. * And/Or occlude the blended part.
  42487. */
  42488. _this.environmentBRDFTexture = null;
  42489. /**
  42490. * Force normal to face away from face.
  42491. */
  42492. _this.forceNormalForward = false;
  42493. /**
  42494. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  42495. * makes the reflect vector face the model (under horizon).
  42496. */
  42497. _this.useHorizonOcclusion = true;
  42498. /**
  42499. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  42500. * too much the area relying on ambient texture to define their ambient occlusion.
  42501. */
  42502. _this.useRadianceOcclusion = true;
  42503. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  42504. return _this;
  42505. }
  42506. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  42507. /**
  42508. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  42509. */
  42510. get: function () {
  42511. return this._PBRMATERIAL_OPAQUE;
  42512. },
  42513. enumerable: true,
  42514. configurable: true
  42515. });
  42516. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  42517. /**
  42518. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42519. */
  42520. get: function () {
  42521. return this._PBRMATERIAL_ALPHATEST;
  42522. },
  42523. enumerable: true,
  42524. configurable: true
  42525. });
  42526. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  42527. /**
  42528. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42529. */
  42530. get: function () {
  42531. return this._PBRMATERIAL_ALPHABLEND;
  42532. },
  42533. enumerable: true,
  42534. configurable: true
  42535. });
  42536. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  42537. /**
  42538. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42539. * They are also discarded below the alpha cutoff threshold to improve performances.
  42540. */
  42541. get: function () {
  42542. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  42543. },
  42544. enumerable: true,
  42545. configurable: true
  42546. });
  42547. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  42548. /**
  42549. * Gets the image processing configuration used either in this material.
  42550. */
  42551. get: function () {
  42552. return this._imageProcessingConfiguration;
  42553. },
  42554. /**
  42555. * Sets the Default image processing configuration used either in the this material.
  42556. *
  42557. * If sets to null, the scene one is in use.
  42558. */
  42559. set: function (value) {
  42560. this._attachImageProcessingConfiguration(value);
  42561. // Ensure the effect will be rebuilt.
  42562. this._markAllSubMeshesAsTexturesDirty();
  42563. },
  42564. enumerable: true,
  42565. configurable: true
  42566. });
  42567. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  42568. /**
  42569. * Gets wether the color curves effect is enabled.
  42570. */
  42571. get: function () {
  42572. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42573. },
  42574. /**
  42575. * Sets wether the color curves effect is enabled.
  42576. */
  42577. set: function (value) {
  42578. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42579. },
  42580. enumerable: true,
  42581. configurable: true
  42582. });
  42583. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42584. /**
  42585. * Gets wether the color grading effect is enabled.
  42586. */
  42587. get: function () {
  42588. return this.imageProcessingConfiguration.colorGradingEnabled;
  42589. },
  42590. /**
  42591. * Gets wether the color grading effect is enabled.
  42592. */
  42593. set: function (value) {
  42594. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42595. },
  42596. enumerable: true,
  42597. configurable: true
  42598. });
  42599. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42600. /**
  42601. * Gets wether tonemapping is enabled or not.
  42602. */
  42603. get: function () {
  42604. return this._imageProcessingConfiguration.toneMappingEnabled;
  42605. },
  42606. /**
  42607. * Sets wether tonemapping is enabled or not
  42608. */
  42609. set: function (value) {
  42610. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42611. },
  42612. enumerable: true,
  42613. configurable: true
  42614. });
  42615. ;
  42616. ;
  42617. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42618. /**
  42619. * The camera exposure used on this material.
  42620. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42621. * This corresponds to a photographic exposure.
  42622. */
  42623. get: function () {
  42624. return this._imageProcessingConfiguration.exposure;
  42625. },
  42626. /**
  42627. * The camera exposure used on this material.
  42628. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42629. * This corresponds to a photographic exposure.
  42630. */
  42631. set: function (value) {
  42632. this._imageProcessingConfiguration.exposure = value;
  42633. },
  42634. enumerable: true,
  42635. configurable: true
  42636. });
  42637. ;
  42638. ;
  42639. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42640. /**
  42641. * Gets The camera contrast used on this material.
  42642. */
  42643. get: function () {
  42644. return this._imageProcessingConfiguration.contrast;
  42645. },
  42646. /**
  42647. * Sets The camera contrast used on this material.
  42648. */
  42649. set: function (value) {
  42650. this._imageProcessingConfiguration.contrast = value;
  42651. },
  42652. enumerable: true,
  42653. configurable: true
  42654. });
  42655. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42656. /**
  42657. * Gets the Color Grading 2D Lookup Texture.
  42658. */
  42659. get: function () {
  42660. return this._imageProcessingConfiguration.colorGradingTexture;
  42661. },
  42662. /**
  42663. * Sets the Color Grading 2D Lookup Texture.
  42664. */
  42665. set: function (value) {
  42666. this._imageProcessingConfiguration.colorGradingTexture = value;
  42667. },
  42668. enumerable: true,
  42669. configurable: true
  42670. });
  42671. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42672. /**
  42673. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42674. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42675. * 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;
  42676. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42677. */
  42678. get: function () {
  42679. return this._imageProcessingConfiguration.colorCurves;
  42680. },
  42681. /**
  42682. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42683. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42684. * 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;
  42685. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42686. */
  42687. set: function (value) {
  42688. this._imageProcessingConfiguration.colorCurves = value;
  42689. },
  42690. enumerable: true,
  42691. configurable: true
  42692. });
  42693. /**
  42694. * Returns the name of this material class.
  42695. */
  42696. PBRMaterial.prototype.getClassName = function () {
  42697. return "PBRMaterial";
  42698. };
  42699. /**
  42700. * Returns an array of the actively used textures.
  42701. * @returns - Array of BaseTextures
  42702. */
  42703. PBRMaterial.prototype.getActiveTextures = function () {
  42704. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42705. if (this._albedoTexture) {
  42706. activeTextures.push(this._albedoTexture);
  42707. }
  42708. if (this._ambientTexture) {
  42709. activeTextures.push(this._ambientTexture);
  42710. }
  42711. if (this._opacityTexture) {
  42712. activeTextures.push(this._opacityTexture);
  42713. }
  42714. if (this._reflectionTexture) {
  42715. activeTextures.push(this._reflectionTexture);
  42716. }
  42717. if (this._emissiveTexture) {
  42718. activeTextures.push(this._emissiveTexture);
  42719. }
  42720. if (this._reflectivityTexture) {
  42721. activeTextures.push(this._reflectivityTexture);
  42722. }
  42723. if (this._metallicTexture) {
  42724. activeTextures.push(this._metallicTexture);
  42725. }
  42726. if (this._microSurfaceTexture) {
  42727. activeTextures.push(this._microSurfaceTexture);
  42728. }
  42729. if (this._bumpTexture) {
  42730. activeTextures.push(this._bumpTexture);
  42731. }
  42732. if (this._lightmapTexture) {
  42733. activeTextures.push(this._lightmapTexture);
  42734. }
  42735. if (this._refractionTexture) {
  42736. activeTextures.push(this._refractionTexture);
  42737. }
  42738. return activeTextures;
  42739. };
  42740. /**
  42741. * Checks to see if a texture is used in the material.
  42742. * @param texture - Base texture to use.
  42743. * @returns - Boolean specifying if a texture is used in the material.
  42744. */
  42745. PBRMaterial.prototype.hasTexture = function (texture) {
  42746. if (_super.prototype.hasTexture.call(this, texture)) {
  42747. return true;
  42748. }
  42749. if (this._albedoTexture === texture) {
  42750. return true;
  42751. }
  42752. if (this._ambientTexture === texture) {
  42753. return true;
  42754. }
  42755. if (this._opacityTexture === texture) {
  42756. return true;
  42757. }
  42758. if (this._reflectionTexture === texture) {
  42759. return true;
  42760. }
  42761. if (this._reflectivityTexture === texture) {
  42762. return true;
  42763. }
  42764. if (this._metallicTexture === texture) {
  42765. return true;
  42766. }
  42767. if (this._microSurfaceTexture === texture) {
  42768. return true;
  42769. }
  42770. if (this._bumpTexture === texture) {
  42771. return true;
  42772. }
  42773. if (this._lightmapTexture === texture) {
  42774. return true;
  42775. }
  42776. if (this._refractionTexture === texture) {
  42777. return true;
  42778. }
  42779. return false;
  42780. };
  42781. /**
  42782. * Makes a duplicate of the current material.
  42783. * @param name - name to use for the new material.
  42784. */
  42785. PBRMaterial.prototype.clone = function (name) {
  42786. var _this = this;
  42787. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  42788. clone.id = name;
  42789. clone.name = name;
  42790. return clone;
  42791. };
  42792. /**
  42793. * Serializes this PBR Material.
  42794. * @returns - An object with the serialized material.
  42795. */
  42796. PBRMaterial.prototype.serialize = function () {
  42797. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42798. serializationObject.customType = "BABYLON.PBRMaterial";
  42799. return serializationObject;
  42800. };
  42801. // Statics
  42802. /**
  42803. * Parses a PBR Material from a serialized object.
  42804. * @param source - Serialized object.
  42805. * @param scene - BJS scene instance.
  42806. * @param rootUrl - url for the scene object
  42807. * @returns - PBRMaterial
  42808. */
  42809. PBRMaterial.Parse = function (source, scene, rootUrl) {
  42810. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  42811. };
  42812. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  42813. /**
  42814. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42815. */
  42816. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  42817. /**
  42818. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42819. */
  42820. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  42821. /**
  42822. * 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.
  42823. * They are also discarded below the alpha cutoff threshold to improve performances.
  42824. */
  42825. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  42826. __decorate([
  42827. BABYLON.serialize(),
  42828. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42829. ], PBRMaterial.prototype, "directIntensity", void 0);
  42830. __decorate([
  42831. BABYLON.serialize(),
  42832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42833. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  42834. __decorate([
  42835. BABYLON.serialize(),
  42836. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42837. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  42838. __decorate([
  42839. BABYLON.serialize(),
  42840. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42841. ], PBRMaterial.prototype, "specularIntensity", void 0);
  42842. __decorate([
  42843. BABYLON.serialize(),
  42844. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42845. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  42846. __decorate([
  42847. BABYLON.serializeAsTexture(),
  42848. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42849. ], PBRMaterial.prototype, "albedoTexture", void 0);
  42850. __decorate([
  42851. BABYLON.serializeAsTexture(),
  42852. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42853. ], PBRMaterial.prototype, "ambientTexture", void 0);
  42854. __decorate([
  42855. BABYLON.serialize(),
  42856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42857. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  42858. __decorate([
  42859. BABYLON.serializeAsTexture(),
  42860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42861. ], PBRMaterial.prototype, "opacityTexture", void 0);
  42862. __decorate([
  42863. BABYLON.serializeAsTexture(),
  42864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42865. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  42866. __decorate([
  42867. BABYLON.serializeAsTexture(),
  42868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42869. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  42870. __decorate([
  42871. BABYLON.serializeAsTexture(),
  42872. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42873. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  42874. __decorate([
  42875. BABYLON.serializeAsTexture(),
  42876. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42877. ], PBRMaterial.prototype, "metallicTexture", void 0);
  42878. __decorate([
  42879. BABYLON.serialize(),
  42880. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42881. ], PBRMaterial.prototype, "metallic", void 0);
  42882. __decorate([
  42883. BABYLON.serialize(),
  42884. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42885. ], PBRMaterial.prototype, "roughness", void 0);
  42886. __decorate([
  42887. BABYLON.serializeAsTexture(),
  42888. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42889. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  42890. __decorate([
  42891. BABYLON.serializeAsTexture(),
  42892. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42893. ], PBRMaterial.prototype, "bumpTexture", void 0);
  42894. __decorate([
  42895. BABYLON.serializeAsTexture(),
  42896. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42897. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  42898. __decorate([
  42899. BABYLON.serializeAsTexture(),
  42900. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42901. ], PBRMaterial.prototype, "refractionTexture", void 0);
  42902. __decorate([
  42903. BABYLON.serializeAsColor3("ambient"),
  42904. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42905. ], PBRMaterial.prototype, "ambientColor", void 0);
  42906. __decorate([
  42907. BABYLON.serializeAsColor3("albedo"),
  42908. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42909. ], PBRMaterial.prototype, "albedoColor", void 0);
  42910. __decorate([
  42911. BABYLON.serializeAsColor3("reflectivity"),
  42912. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42913. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  42914. __decorate([
  42915. BABYLON.serializeAsColor3("reflection"),
  42916. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42917. ], PBRMaterial.prototype, "reflectionColor", void 0);
  42918. __decorate([
  42919. BABYLON.serializeAsColor3("emissive"),
  42920. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42921. ], PBRMaterial.prototype, "emissiveColor", void 0);
  42922. __decorate([
  42923. BABYLON.serialize(),
  42924. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42925. ], PBRMaterial.prototype, "microSurface", void 0);
  42926. __decorate([
  42927. BABYLON.serialize(),
  42928. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42929. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  42930. __decorate([
  42931. BABYLON.serialize(),
  42932. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42933. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  42934. __decorate([
  42935. BABYLON.serialize(),
  42936. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42937. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  42938. __decorate([
  42939. BABYLON.serialize(),
  42940. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42941. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42942. __decorate([
  42943. BABYLON.serialize(),
  42944. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42945. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  42946. __decorate([
  42947. BABYLON.serialize(),
  42948. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42949. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  42950. __decorate([
  42951. BABYLON.serialize(),
  42952. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42953. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  42954. __decorate([
  42955. BABYLON.serialize(),
  42956. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42957. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  42958. __decorate([
  42959. BABYLON.serialize(),
  42960. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42961. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  42962. __decorate([
  42963. BABYLON.serialize(),
  42964. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42965. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  42966. __decorate([
  42967. BABYLON.serialize(),
  42968. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42969. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  42970. __decorate([
  42971. BABYLON.serialize(),
  42972. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42973. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  42974. __decorate([
  42975. BABYLON.serialize(),
  42976. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42977. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  42978. __decorate([
  42979. BABYLON.serialize(),
  42980. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42981. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  42982. __decorate([
  42983. BABYLON.serialize(),
  42984. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42985. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  42986. __decorate([
  42987. BABYLON.serialize(),
  42988. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42989. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  42990. __decorate([
  42991. BABYLON.serialize(),
  42992. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42993. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  42994. __decorate([
  42995. BABYLON.serialize(),
  42996. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42997. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42998. __decorate([
  42999. BABYLON.serialize(),
  43000. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43001. ], PBRMaterial.prototype, "useParallax", void 0);
  43002. __decorate([
  43003. BABYLON.serialize(),
  43004. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43005. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  43006. __decorate([
  43007. BABYLON.serialize(),
  43008. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43009. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  43010. __decorate([
  43011. BABYLON.serialize(),
  43012. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43013. ], PBRMaterial.prototype, "disableLighting", void 0);
  43014. __decorate([
  43015. BABYLON.serialize(),
  43016. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43017. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  43018. __decorate([
  43019. BABYLON.serialize(),
  43020. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43021. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  43022. __decorate([
  43023. BABYLON.serialize(),
  43024. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43025. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  43026. __decorate([
  43027. BABYLON.serialize(),
  43028. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43029. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  43030. __decorate([
  43031. BABYLON.serialize(),
  43032. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43033. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  43034. __decorate([
  43035. BABYLON.serialize(),
  43036. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43037. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  43038. __decorate([
  43039. BABYLON.serialize(),
  43040. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43041. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  43042. __decorate([
  43043. BABYLON.serializeAsTexture(),
  43044. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43045. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  43046. __decorate([
  43047. BABYLON.serialize(),
  43048. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43049. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  43050. __decorate([
  43051. BABYLON.serialize(),
  43052. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43053. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  43054. __decorate([
  43055. BABYLON.serialize(),
  43056. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43057. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  43058. return PBRMaterial;
  43059. }(BABYLON.PBRBaseMaterial));
  43060. BABYLON.PBRMaterial = PBRMaterial;
  43061. })(BABYLON || (BABYLON = {}));
  43062. //# sourceMappingURL=babylon.pbrMaterial.js.map
  43063. var BABYLON;
  43064. (function (BABYLON) {
  43065. /**
  43066. * The PBR material of BJS following the metal roughness convention.
  43067. *
  43068. * This fits to the PBR convention in the GLTF definition:
  43069. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  43070. */
  43071. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  43072. __extends(PBRMetallicRoughnessMaterial, _super);
  43073. /**
  43074. * Instantiates a new PBRMetalRoughnessMaterial instance.
  43075. *
  43076. * @param name The material name
  43077. * @param scene The scene the material will be use in.
  43078. */
  43079. function PBRMetallicRoughnessMaterial(name, scene) {
  43080. var _this = _super.call(this, name, scene) || this;
  43081. _this._useRoughnessFromMetallicTextureAlpha = false;
  43082. _this._useRoughnessFromMetallicTextureGreen = true;
  43083. _this._useMetallnessFromMetallicTextureBlue = true;
  43084. _this.metallic = 1.0;
  43085. _this.roughness = 1.0;
  43086. return _this;
  43087. }
  43088. /**
  43089. * Return the currrent class name of the material.
  43090. */
  43091. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  43092. return "PBRMetallicRoughnessMaterial";
  43093. };
  43094. /**
  43095. * Return the active textures of the material.
  43096. */
  43097. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  43098. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43099. if (this.baseTexture) {
  43100. activeTextures.push(this.baseTexture);
  43101. }
  43102. if (this.metallicRoughnessTexture) {
  43103. activeTextures.push(this.metallicRoughnessTexture);
  43104. }
  43105. return activeTextures;
  43106. };
  43107. /**
  43108. * Checks to see if a texture is used in the material.
  43109. * @param texture - Base texture to use.
  43110. * @returns - Boolean specifying if a texture is used in the material.
  43111. */
  43112. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  43113. if (_super.prototype.hasTexture.call(this, texture)) {
  43114. return true;
  43115. }
  43116. if (this.baseTexture === texture) {
  43117. return true;
  43118. }
  43119. if (this.metallicRoughnessTexture === texture) {
  43120. return true;
  43121. }
  43122. return false;
  43123. };
  43124. /**
  43125. * Makes a duplicate of the current material.
  43126. * @param name - name to use for the new material.
  43127. */
  43128. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  43129. var _this = this;
  43130. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  43131. clone.id = name;
  43132. clone.name = name;
  43133. return clone;
  43134. };
  43135. /**
  43136. * Serialize the material to a parsable JSON object.
  43137. */
  43138. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  43139. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43140. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  43141. return serializationObject;
  43142. };
  43143. /**
  43144. * Parses a JSON object correponding to the serialize function.
  43145. */
  43146. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  43147. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  43148. };
  43149. __decorate([
  43150. BABYLON.serializeAsColor3(),
  43151. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43152. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  43153. __decorate([
  43154. BABYLON.serializeAsTexture(),
  43155. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43156. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  43157. __decorate([
  43158. BABYLON.serialize(),
  43159. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43160. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  43161. __decorate([
  43162. BABYLON.serialize(),
  43163. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43164. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  43165. __decorate([
  43166. BABYLON.serializeAsTexture(),
  43167. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  43168. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  43169. return PBRMetallicRoughnessMaterial;
  43170. }(BABYLON.PBRBaseSimpleMaterial));
  43171. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  43172. })(BABYLON || (BABYLON = {}));
  43173. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  43174. var BABYLON;
  43175. (function (BABYLON) {
  43176. /**
  43177. * The PBR material of BJS following the specular glossiness convention.
  43178. *
  43179. * This fits to the PBR convention in the GLTF definition:
  43180. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  43181. */
  43182. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  43183. __extends(PBRSpecularGlossinessMaterial, _super);
  43184. /**
  43185. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  43186. *
  43187. * @param name The material name
  43188. * @param scene The scene the material will be use in.
  43189. */
  43190. function PBRSpecularGlossinessMaterial(name, scene) {
  43191. var _this = _super.call(this, name, scene) || this;
  43192. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  43193. return _this;
  43194. }
  43195. /**
  43196. * Return the currrent class name of the material.
  43197. */
  43198. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  43199. return "PBRSpecularGlossinessMaterial";
  43200. };
  43201. /**
  43202. * Return the active textures of the material.
  43203. */
  43204. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  43205. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43206. if (this.diffuseTexture) {
  43207. activeTextures.push(this.diffuseTexture);
  43208. }
  43209. if (this.specularGlossinessTexture) {
  43210. activeTextures.push(this.specularGlossinessTexture);
  43211. }
  43212. return activeTextures;
  43213. };
  43214. /**
  43215. * Checks to see if a texture is used in the material.
  43216. * @param texture - Base texture to use.
  43217. * @returns - Boolean specifying if a texture is used in the material.
  43218. */
  43219. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  43220. if (_super.prototype.hasTexture.call(this, texture)) {
  43221. return true;
  43222. }
  43223. if (this.diffuseTexture === texture) {
  43224. return true;
  43225. }
  43226. if (this.specularGlossinessTexture === texture) {
  43227. return true;
  43228. }
  43229. return false;
  43230. };
  43231. /**
  43232. * Makes a duplicate of the current material.
  43233. * @param name - name to use for the new material.
  43234. */
  43235. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  43236. var _this = this;
  43237. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  43238. clone.id = name;
  43239. clone.name = name;
  43240. return clone;
  43241. };
  43242. /**
  43243. * Serialize the material to a parsable JSON object.
  43244. */
  43245. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  43246. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43247. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  43248. return serializationObject;
  43249. };
  43250. /**
  43251. * Parses a JSON object correponding to the serialize function.
  43252. */
  43253. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  43254. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  43255. };
  43256. __decorate([
  43257. BABYLON.serializeAsColor3("diffuse"),
  43258. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43259. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  43260. __decorate([
  43261. BABYLON.serializeAsTexture(),
  43262. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43263. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  43264. __decorate([
  43265. BABYLON.serializeAsColor3("specular"),
  43266. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  43267. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  43268. __decorate([
  43269. BABYLON.serialize(),
  43270. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  43271. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  43272. __decorate([
  43273. BABYLON.serializeAsTexture(),
  43274. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  43275. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  43276. return PBRSpecularGlossinessMaterial;
  43277. }(BABYLON.PBRBaseSimpleMaterial));
  43278. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  43279. })(BABYLON || (BABYLON = {}));
  43280. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  43281. var BABYLON;
  43282. (function (BABYLON) {
  43283. BABYLON.CameraInputTypes = {};
  43284. var CameraInputsManager = /** @class */ (function () {
  43285. function CameraInputsManager(camera) {
  43286. this.attached = {};
  43287. this.camera = camera;
  43288. this.checkInputs = function () { };
  43289. }
  43290. /**
  43291. * Add an input method to a camera.
  43292. * builtin inputs example: camera.inputs.addGamepad();
  43293. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  43294. * @param input camera input method
  43295. */
  43296. CameraInputsManager.prototype.add = function (input) {
  43297. var type = input.getSimpleName();
  43298. if (this.attached[type]) {
  43299. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  43300. return;
  43301. }
  43302. this.attached[type] = input;
  43303. input.camera = this.camera;
  43304. //for checkInputs, we are dynamically creating a function
  43305. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  43306. if (input.checkInputs) {
  43307. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43308. }
  43309. if (this.attachedElement) {
  43310. input.attachControl(this.attachedElement);
  43311. }
  43312. };
  43313. /**
  43314. * Remove a specific input method from a camera
  43315. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  43316. * @param inputToRemove camera input method
  43317. */
  43318. CameraInputsManager.prototype.remove = function (inputToRemove) {
  43319. for (var cam in this.attached) {
  43320. var input = this.attached[cam];
  43321. if (input === inputToRemove) {
  43322. input.detachControl(this.attachedElement);
  43323. input.camera = null;
  43324. delete this.attached[cam];
  43325. this.rebuildInputCheck();
  43326. }
  43327. }
  43328. };
  43329. CameraInputsManager.prototype.removeByType = function (inputType) {
  43330. for (var cam in this.attached) {
  43331. var input = this.attached[cam];
  43332. if (input.getClassName() === inputType) {
  43333. input.detachControl(this.attachedElement);
  43334. input.camera = null;
  43335. delete this.attached[cam];
  43336. this.rebuildInputCheck();
  43337. }
  43338. }
  43339. };
  43340. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  43341. var current = this.checkInputs;
  43342. return function () {
  43343. current();
  43344. fn();
  43345. };
  43346. };
  43347. CameraInputsManager.prototype.attachInput = function (input) {
  43348. if (this.attachedElement) {
  43349. input.attachControl(this.attachedElement, this.noPreventDefault);
  43350. }
  43351. };
  43352. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  43353. if (noPreventDefault === void 0) { noPreventDefault = false; }
  43354. if (this.attachedElement) {
  43355. return;
  43356. }
  43357. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  43358. this.attachedElement = element;
  43359. this.noPreventDefault = noPreventDefault;
  43360. for (var cam in this.attached) {
  43361. this.attached[cam].attachControl(element, noPreventDefault);
  43362. }
  43363. };
  43364. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  43365. if (disconnect === void 0) { disconnect = false; }
  43366. if (this.attachedElement !== element) {
  43367. return;
  43368. }
  43369. for (var cam in this.attached) {
  43370. this.attached[cam].detachControl(element);
  43371. if (disconnect) {
  43372. this.attached[cam].camera = null;
  43373. }
  43374. }
  43375. this.attachedElement = null;
  43376. };
  43377. CameraInputsManager.prototype.rebuildInputCheck = function () {
  43378. this.checkInputs = function () { };
  43379. for (var cam in this.attached) {
  43380. var input = this.attached[cam];
  43381. if (input.checkInputs) {
  43382. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43383. }
  43384. }
  43385. };
  43386. /**
  43387. * Remove all attached input methods from a camera
  43388. */
  43389. CameraInputsManager.prototype.clear = function () {
  43390. if (this.attachedElement) {
  43391. this.detachElement(this.attachedElement, true);
  43392. }
  43393. this.attached = {};
  43394. this.attachedElement = null;
  43395. this.checkInputs = function () { };
  43396. };
  43397. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  43398. var inputs = {};
  43399. for (var cam in this.attached) {
  43400. var input = this.attached[cam];
  43401. var res = BABYLON.SerializationHelper.Serialize(input);
  43402. inputs[input.getClassName()] = res;
  43403. }
  43404. serializedCamera.inputsmgr = inputs;
  43405. };
  43406. CameraInputsManager.prototype.parse = function (parsedCamera) {
  43407. var parsedInputs = parsedCamera.inputsmgr;
  43408. if (parsedInputs) {
  43409. this.clear();
  43410. for (var n in parsedInputs) {
  43411. var construct = BABYLON.CameraInputTypes[n];
  43412. if (construct) {
  43413. var parsedinput = parsedInputs[n];
  43414. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  43415. this.add(input);
  43416. }
  43417. }
  43418. }
  43419. else {
  43420. //2016-03-08 this part is for managing backward compatibility
  43421. for (var n in this.attached) {
  43422. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  43423. if (construct) {
  43424. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  43425. this.remove(this.attached[n]);
  43426. this.add(input);
  43427. }
  43428. }
  43429. }
  43430. };
  43431. return CameraInputsManager;
  43432. }());
  43433. BABYLON.CameraInputsManager = CameraInputsManager;
  43434. })(BABYLON || (BABYLON = {}));
  43435. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  43436. var BABYLON;
  43437. (function (BABYLON) {
  43438. var TargetCamera = /** @class */ (function (_super) {
  43439. __extends(TargetCamera, _super);
  43440. function TargetCamera(name, position, scene) {
  43441. var _this = _super.call(this, name, position, scene) || this;
  43442. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43443. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  43444. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  43445. _this.speed = 2.0;
  43446. _this.noRotationConstraint = false;
  43447. _this.lockedTarget = null;
  43448. _this._currentTarget = BABYLON.Vector3.Zero();
  43449. _this._viewMatrix = BABYLON.Matrix.Zero();
  43450. _this._camMatrix = BABYLON.Matrix.Zero();
  43451. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  43452. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  43453. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  43454. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  43455. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  43456. _this._lookAtTemp = BABYLON.Matrix.Zero();
  43457. _this._tempMatrix = BABYLON.Matrix.Zero();
  43458. return _this;
  43459. }
  43460. TargetCamera.prototype.getFrontPosition = function (distance) {
  43461. this.getWorldMatrix();
  43462. var direction = this.getTarget().subtract(this.position);
  43463. direction.normalize();
  43464. direction.scaleInPlace(distance);
  43465. return this.globalPosition.add(direction);
  43466. };
  43467. TargetCamera.prototype._getLockedTargetPosition = function () {
  43468. if (!this.lockedTarget) {
  43469. return null;
  43470. }
  43471. if (this.lockedTarget.absolutePosition) {
  43472. this.lockedTarget.computeWorldMatrix();
  43473. }
  43474. return this.lockedTarget.absolutePosition || this.lockedTarget;
  43475. };
  43476. TargetCamera.prototype.storeState = function () {
  43477. this._storedPosition = this.position.clone();
  43478. this._storedRotation = this.rotation.clone();
  43479. if (this.rotationQuaternion) {
  43480. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  43481. }
  43482. return _super.prototype.storeState.call(this);
  43483. };
  43484. /**
  43485. * Restored camera state. You must call storeState() first
  43486. */
  43487. TargetCamera.prototype._restoreStateValues = function () {
  43488. if (!_super.prototype._restoreStateValues.call(this)) {
  43489. return false;
  43490. }
  43491. this.position = this._storedPosition.clone();
  43492. this.rotation = this._storedRotation.clone();
  43493. if (this.rotationQuaternion) {
  43494. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  43495. }
  43496. this.cameraDirection.copyFromFloats(0, 0, 0);
  43497. this.cameraRotation.copyFromFloats(0, 0);
  43498. return true;
  43499. };
  43500. // Cache
  43501. TargetCamera.prototype._initCache = function () {
  43502. _super.prototype._initCache.call(this);
  43503. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43504. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43505. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43506. };
  43507. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  43508. if (!ignoreParentClass) {
  43509. _super.prototype._updateCache.call(this);
  43510. }
  43511. var lockedTargetPosition = this._getLockedTargetPosition();
  43512. if (!lockedTargetPosition) {
  43513. this._cache.lockedTarget = null;
  43514. }
  43515. else {
  43516. if (!this._cache.lockedTarget) {
  43517. this._cache.lockedTarget = lockedTargetPosition.clone();
  43518. }
  43519. else {
  43520. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  43521. }
  43522. }
  43523. this._cache.rotation.copyFrom(this.rotation);
  43524. if (this.rotationQuaternion)
  43525. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43526. };
  43527. // Synchronized
  43528. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  43529. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  43530. return false;
  43531. }
  43532. var lockedTargetPosition = this._getLockedTargetPosition();
  43533. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  43534. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  43535. };
  43536. // Methods
  43537. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  43538. var engine = this.getEngine();
  43539. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  43540. };
  43541. // Target
  43542. TargetCamera.prototype.setTarget = function (target) {
  43543. this.upVector.normalize();
  43544. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  43545. this._camMatrix.invert();
  43546. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  43547. var vDir = target.subtract(this.position);
  43548. if (vDir.x >= 0.0) {
  43549. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  43550. }
  43551. else {
  43552. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  43553. }
  43554. this.rotation.z = 0;
  43555. if (isNaN(this.rotation.x)) {
  43556. this.rotation.x = 0;
  43557. }
  43558. if (isNaN(this.rotation.y)) {
  43559. this.rotation.y = 0;
  43560. }
  43561. if (isNaN(this.rotation.z)) {
  43562. this.rotation.z = 0;
  43563. }
  43564. if (this.rotationQuaternion) {
  43565. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43566. }
  43567. };
  43568. /**
  43569. * Return the current target position of the camera. This value is expressed in local space.
  43570. */
  43571. TargetCamera.prototype.getTarget = function () {
  43572. return this._currentTarget;
  43573. };
  43574. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43575. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43576. };
  43577. TargetCamera.prototype._updatePosition = function () {
  43578. if (this.parent) {
  43579. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43580. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43581. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43582. return;
  43583. }
  43584. this.position.addInPlace(this.cameraDirection);
  43585. };
  43586. TargetCamera.prototype._checkInputs = function () {
  43587. var needToMove = this._decideIfNeedsToMove();
  43588. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43589. // Move
  43590. if (needToMove) {
  43591. this._updatePosition();
  43592. }
  43593. // Rotate
  43594. if (needToRotate) {
  43595. this.rotation.x += this.cameraRotation.x;
  43596. this.rotation.y += this.cameraRotation.y;
  43597. //rotate, if quaternion is set and rotation was used
  43598. if (this.rotationQuaternion) {
  43599. var len = this.rotation.lengthSquared();
  43600. if (len) {
  43601. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43602. }
  43603. }
  43604. if (!this.noRotationConstraint) {
  43605. var limit = (Math.PI / 2) * 0.95;
  43606. if (this.rotation.x > limit)
  43607. this.rotation.x = limit;
  43608. if (this.rotation.x < -limit)
  43609. this.rotation.x = -limit;
  43610. }
  43611. }
  43612. // Inertia
  43613. if (needToMove) {
  43614. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43615. this.cameraDirection.x = 0;
  43616. }
  43617. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43618. this.cameraDirection.y = 0;
  43619. }
  43620. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43621. this.cameraDirection.z = 0;
  43622. }
  43623. this.cameraDirection.scaleInPlace(this.inertia);
  43624. }
  43625. if (needToRotate) {
  43626. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43627. this.cameraRotation.x = 0;
  43628. }
  43629. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43630. this.cameraRotation.y = 0;
  43631. }
  43632. this.cameraRotation.scaleInPlace(this.inertia);
  43633. }
  43634. _super.prototype._checkInputs.call(this);
  43635. };
  43636. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43637. if (this.rotationQuaternion) {
  43638. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43639. }
  43640. else {
  43641. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43642. }
  43643. //update the up vector!
  43644. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43645. };
  43646. TargetCamera.prototype._getViewMatrix = function () {
  43647. if (this.lockedTarget) {
  43648. this.setTarget(this._getLockedTargetPosition());
  43649. }
  43650. // Compute
  43651. this._updateCameraRotationMatrix();
  43652. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43653. // Computing target and final matrix
  43654. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43655. if (this.getScene().useRightHandedSystem) {
  43656. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43657. }
  43658. else {
  43659. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43660. }
  43661. return this._viewMatrix;
  43662. };
  43663. /**
  43664. * @override
  43665. * Override Camera.createRigCamera
  43666. */
  43667. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43668. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43669. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43670. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43671. if (!this.rotationQuaternion) {
  43672. this.rotationQuaternion = new BABYLON.Quaternion();
  43673. }
  43674. rigCamera._cameraRigParams = {};
  43675. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43676. }
  43677. return rigCamera;
  43678. }
  43679. return null;
  43680. };
  43681. /**
  43682. * @override
  43683. * Override Camera._updateRigCameras
  43684. */
  43685. TargetCamera.prototype._updateRigCameras = function () {
  43686. var camLeft = this._rigCameras[0];
  43687. var camRight = this._rigCameras[1];
  43688. switch (this.cameraRigMode) {
  43689. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43690. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43691. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43692. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43693. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43694. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43695. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43696. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43697. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43698. camLeft.setTarget(this.getTarget());
  43699. camRight.setTarget(this.getTarget());
  43700. break;
  43701. case BABYLON.Camera.RIG_MODE_VR:
  43702. if (camLeft.rotationQuaternion) {
  43703. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43704. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43705. }
  43706. else {
  43707. camLeft.rotation.copyFrom(this.rotation);
  43708. camRight.rotation.copyFrom(this.rotation);
  43709. }
  43710. camLeft.position.copyFrom(this.position);
  43711. camRight.position.copyFrom(this.position);
  43712. break;
  43713. }
  43714. _super.prototype._updateRigCameras.call(this);
  43715. };
  43716. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43717. if (!this._rigCamTransformMatrix) {
  43718. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43719. }
  43720. var target = this.getTarget();
  43721. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43722. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43723. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43724. };
  43725. TargetCamera.prototype.getClassName = function () {
  43726. return "TargetCamera";
  43727. };
  43728. __decorate([
  43729. BABYLON.serializeAsVector3()
  43730. ], TargetCamera.prototype, "rotation", void 0);
  43731. __decorate([
  43732. BABYLON.serialize()
  43733. ], TargetCamera.prototype, "speed", void 0);
  43734. __decorate([
  43735. BABYLON.serializeAsMeshReference("lockedTargetId")
  43736. ], TargetCamera.prototype, "lockedTarget", void 0);
  43737. return TargetCamera;
  43738. }(BABYLON.Camera));
  43739. BABYLON.TargetCamera = TargetCamera;
  43740. })(BABYLON || (BABYLON = {}));
  43741. //# sourceMappingURL=babylon.targetCamera.js.map
  43742. var BABYLON;
  43743. (function (BABYLON) {
  43744. var FreeCameraMouseInput = /** @class */ (function () {
  43745. function FreeCameraMouseInput(touchEnabled) {
  43746. if (touchEnabled === void 0) { touchEnabled = true; }
  43747. this.touchEnabled = touchEnabled;
  43748. this.buttons = [0, 1, 2];
  43749. this.angularSensibility = 2000.0;
  43750. this.previousPosition = null;
  43751. }
  43752. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43753. var _this = this;
  43754. var engine = this.camera.getEngine();
  43755. if (!this._pointerInput) {
  43756. this._pointerInput = function (p, s) {
  43757. var evt = p.event;
  43758. if (engine.isInVRExclusivePointerMode) {
  43759. return;
  43760. }
  43761. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43762. return;
  43763. }
  43764. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43765. return;
  43766. }
  43767. var srcElement = (evt.srcElement || evt.target);
  43768. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43769. try {
  43770. srcElement.setPointerCapture(evt.pointerId);
  43771. }
  43772. catch (e) {
  43773. //Nothing to do with the error. Execution will continue.
  43774. }
  43775. _this.previousPosition = {
  43776. x: evt.clientX,
  43777. y: evt.clientY
  43778. };
  43779. if (!noPreventDefault) {
  43780. evt.preventDefault();
  43781. element.focus();
  43782. }
  43783. }
  43784. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43785. try {
  43786. srcElement.releasePointerCapture(evt.pointerId);
  43787. }
  43788. catch (e) {
  43789. //Nothing to do with the error.
  43790. }
  43791. _this.previousPosition = null;
  43792. if (!noPreventDefault) {
  43793. evt.preventDefault();
  43794. }
  43795. }
  43796. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43797. if (!_this.previousPosition || engine.isPointerLock) {
  43798. return;
  43799. }
  43800. var offsetX = evt.clientX - _this.previousPosition.x;
  43801. var offsetY = evt.clientY - _this.previousPosition.y;
  43802. if (_this.camera.getScene().useRightHandedSystem) {
  43803. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43804. }
  43805. else {
  43806. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43807. }
  43808. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43809. _this.previousPosition = {
  43810. x: evt.clientX,
  43811. y: evt.clientY
  43812. };
  43813. if (!noPreventDefault) {
  43814. evt.preventDefault();
  43815. }
  43816. }
  43817. };
  43818. }
  43819. this._onMouseMove = function (evt) {
  43820. if (!engine.isPointerLock) {
  43821. return;
  43822. }
  43823. if (engine.isInVRExclusivePointerMode) {
  43824. return;
  43825. }
  43826. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43827. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43828. if (_this.camera.getScene().useRightHandedSystem) {
  43829. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43830. }
  43831. else {
  43832. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43833. }
  43834. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43835. _this.previousPosition = null;
  43836. if (!noPreventDefault) {
  43837. evt.preventDefault();
  43838. }
  43839. };
  43840. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  43841. element.addEventListener("mousemove", this._onMouseMove, false);
  43842. };
  43843. FreeCameraMouseInput.prototype.detachControl = function (element) {
  43844. if (this._observer && element) {
  43845. this.camera.getScene().onPointerObservable.remove(this._observer);
  43846. if (this._onMouseMove) {
  43847. element.removeEventListener("mousemove", this._onMouseMove);
  43848. }
  43849. this._observer = null;
  43850. this._onMouseMove = null;
  43851. this.previousPosition = null;
  43852. }
  43853. };
  43854. FreeCameraMouseInput.prototype.getClassName = function () {
  43855. return "FreeCameraMouseInput";
  43856. };
  43857. FreeCameraMouseInput.prototype.getSimpleName = function () {
  43858. return "mouse";
  43859. };
  43860. __decorate([
  43861. BABYLON.serialize()
  43862. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  43863. __decorate([
  43864. BABYLON.serialize()
  43865. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  43866. return FreeCameraMouseInput;
  43867. }());
  43868. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  43869. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  43870. })(BABYLON || (BABYLON = {}));
  43871. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  43872. var BABYLON;
  43873. (function (BABYLON) {
  43874. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  43875. function FreeCameraKeyboardMoveInput() {
  43876. this._keys = new Array();
  43877. this.keysUp = [38];
  43878. this.keysDown = [40];
  43879. this.keysLeft = [37];
  43880. this.keysRight = [39];
  43881. }
  43882. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43883. var _this = this;
  43884. if (this._onCanvasBlurObserver) {
  43885. return;
  43886. }
  43887. this._scene = this.camera.getScene();
  43888. this._engine = this._scene.getEngine();
  43889. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43890. _this._keys = [];
  43891. });
  43892. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43893. var evt = info.event;
  43894. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43895. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43896. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43897. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43898. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43899. var index = _this._keys.indexOf(evt.keyCode);
  43900. if (index === -1) {
  43901. _this._keys.push(evt.keyCode);
  43902. }
  43903. if (!noPreventDefault) {
  43904. evt.preventDefault();
  43905. }
  43906. }
  43907. }
  43908. else {
  43909. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43910. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43911. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43912. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43913. var index = _this._keys.indexOf(evt.keyCode);
  43914. if (index >= 0) {
  43915. _this._keys.splice(index, 1);
  43916. }
  43917. if (!noPreventDefault) {
  43918. evt.preventDefault();
  43919. }
  43920. }
  43921. }
  43922. });
  43923. };
  43924. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43925. if (this._scene) {
  43926. if (this._onKeyboardObserver) {
  43927. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43928. }
  43929. if (this._onCanvasBlurObserver) {
  43930. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43931. }
  43932. this._onKeyboardObserver = null;
  43933. this._onCanvasBlurObserver = null;
  43934. }
  43935. this._keys = [];
  43936. };
  43937. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43938. if (this._onKeyboardObserver) {
  43939. var camera = this.camera;
  43940. // Keyboard
  43941. for (var index = 0; index < this._keys.length; index++) {
  43942. var keyCode = this._keys[index];
  43943. var speed = camera._computeLocalCameraSpeed();
  43944. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43945. camera._localDirection.copyFromFloats(-speed, 0, 0);
  43946. }
  43947. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43948. camera._localDirection.copyFromFloats(0, 0, speed);
  43949. }
  43950. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43951. camera._localDirection.copyFromFloats(speed, 0, 0);
  43952. }
  43953. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43954. camera._localDirection.copyFromFloats(0, 0, -speed);
  43955. }
  43956. if (camera.getScene().useRightHandedSystem) {
  43957. camera._localDirection.z *= -1;
  43958. }
  43959. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  43960. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  43961. camera.cameraDirection.addInPlace(camera._transformedDirection);
  43962. }
  43963. }
  43964. };
  43965. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  43966. return "FreeCameraKeyboardMoveInput";
  43967. };
  43968. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  43969. this._keys = [];
  43970. };
  43971. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43972. return "keyboard";
  43973. };
  43974. __decorate([
  43975. BABYLON.serialize()
  43976. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43977. __decorate([
  43978. BABYLON.serialize()
  43979. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43980. __decorate([
  43981. BABYLON.serialize()
  43982. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43983. __decorate([
  43984. BABYLON.serialize()
  43985. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43986. return FreeCameraKeyboardMoveInput;
  43987. }());
  43988. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  43989. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  43990. })(BABYLON || (BABYLON = {}));
  43991. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  43992. var BABYLON;
  43993. (function (BABYLON) {
  43994. var FreeCameraInputsManager = /** @class */ (function (_super) {
  43995. __extends(FreeCameraInputsManager, _super);
  43996. function FreeCameraInputsManager(camera) {
  43997. return _super.call(this, camera) || this;
  43998. }
  43999. FreeCameraInputsManager.prototype.addKeyboard = function () {
  44000. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  44001. return this;
  44002. };
  44003. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  44004. if (touchEnabled === void 0) { touchEnabled = true; }
  44005. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  44006. return this;
  44007. };
  44008. FreeCameraInputsManager.prototype.addGamepad = function () {
  44009. this.add(new BABYLON.FreeCameraGamepadInput());
  44010. return this;
  44011. };
  44012. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  44013. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  44014. return this;
  44015. };
  44016. FreeCameraInputsManager.prototype.addTouch = function () {
  44017. this.add(new BABYLON.FreeCameraTouchInput());
  44018. return this;
  44019. };
  44020. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  44021. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  44022. return this;
  44023. };
  44024. return FreeCameraInputsManager;
  44025. }(BABYLON.CameraInputsManager));
  44026. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  44027. })(BABYLON || (BABYLON = {}));
  44028. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  44029. var BABYLON;
  44030. (function (BABYLON) {
  44031. var FreeCamera = /** @class */ (function (_super) {
  44032. __extends(FreeCamera, _super);
  44033. function FreeCamera(name, position, scene) {
  44034. var _this = _super.call(this, name, position, scene) || this;
  44035. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  44036. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  44037. _this.checkCollisions = false;
  44038. _this.applyGravity = false;
  44039. _this._needMoveForGravity = false;
  44040. _this._oldPosition = BABYLON.Vector3.Zero();
  44041. _this._diffPosition = BABYLON.Vector3.Zero();
  44042. _this._newPosition = BABYLON.Vector3.Zero();
  44043. // Collisions
  44044. _this._collisionMask = -1;
  44045. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44046. if (collidedMesh === void 0) { collidedMesh = null; }
  44047. //TODO move this to the collision coordinator!
  44048. if (_this.getScene().workerCollisions)
  44049. newPosition.multiplyInPlace(_this._collider._radius);
  44050. var updatePosition = function (newPos) {
  44051. _this._newPosition.copyFrom(newPos);
  44052. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  44053. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  44054. _this.position.addInPlace(_this._diffPosition);
  44055. if (_this.onCollide && collidedMesh) {
  44056. _this.onCollide(collidedMesh);
  44057. }
  44058. }
  44059. };
  44060. updatePosition(newPosition);
  44061. };
  44062. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  44063. _this.inputs.addKeyboard().addMouse();
  44064. return _this;
  44065. }
  44066. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  44067. //-- begin properties for backward compatibility for inputs
  44068. /**
  44069. * Gets the input sensibility for a mouse input. (default is 2000.0)
  44070. * Higher values reduce sensitivity.
  44071. */
  44072. get: function () {
  44073. var mouse = this.inputs.attached["mouse"];
  44074. if (mouse)
  44075. return mouse.angularSensibility;
  44076. return 0;
  44077. },
  44078. /**
  44079. * Sets the input sensibility for a mouse input. (default is 2000.0)
  44080. * Higher values reduce sensitivity.
  44081. */
  44082. set: function (value) {
  44083. var mouse = this.inputs.attached["mouse"];
  44084. if (mouse)
  44085. mouse.angularSensibility = value;
  44086. },
  44087. enumerable: true,
  44088. configurable: true
  44089. });
  44090. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  44091. get: function () {
  44092. var keyboard = this.inputs.attached["keyboard"];
  44093. if (keyboard)
  44094. return keyboard.keysUp;
  44095. return [];
  44096. },
  44097. set: function (value) {
  44098. var keyboard = this.inputs.attached["keyboard"];
  44099. if (keyboard)
  44100. keyboard.keysUp = value;
  44101. },
  44102. enumerable: true,
  44103. configurable: true
  44104. });
  44105. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  44106. get: function () {
  44107. var keyboard = this.inputs.attached["keyboard"];
  44108. if (keyboard)
  44109. return keyboard.keysDown;
  44110. return [];
  44111. },
  44112. set: function (value) {
  44113. var keyboard = this.inputs.attached["keyboard"];
  44114. if (keyboard)
  44115. keyboard.keysDown = value;
  44116. },
  44117. enumerable: true,
  44118. configurable: true
  44119. });
  44120. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  44121. get: function () {
  44122. var keyboard = this.inputs.attached["keyboard"];
  44123. if (keyboard)
  44124. return keyboard.keysLeft;
  44125. return [];
  44126. },
  44127. set: function (value) {
  44128. var keyboard = this.inputs.attached["keyboard"];
  44129. if (keyboard)
  44130. keyboard.keysLeft = value;
  44131. },
  44132. enumerable: true,
  44133. configurable: true
  44134. });
  44135. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  44136. get: function () {
  44137. var keyboard = this.inputs.attached["keyboard"];
  44138. if (keyboard)
  44139. return keyboard.keysRight;
  44140. return [];
  44141. },
  44142. set: function (value) {
  44143. var keyboard = this.inputs.attached["keyboard"];
  44144. if (keyboard)
  44145. keyboard.keysRight = value;
  44146. },
  44147. enumerable: true,
  44148. configurable: true
  44149. });
  44150. // Controls
  44151. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  44152. this.inputs.attachElement(element, noPreventDefault);
  44153. };
  44154. FreeCamera.prototype.detachControl = function (element) {
  44155. this.inputs.detachElement(element);
  44156. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  44157. this.cameraRotation = new BABYLON.Vector2(0, 0);
  44158. };
  44159. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  44160. get: function () {
  44161. return this._collisionMask;
  44162. },
  44163. set: function (mask) {
  44164. this._collisionMask = !isNaN(mask) ? mask : -1;
  44165. },
  44166. enumerable: true,
  44167. configurable: true
  44168. });
  44169. FreeCamera.prototype._collideWithWorld = function (displacement) {
  44170. var globalPosition;
  44171. if (this.parent) {
  44172. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  44173. }
  44174. else {
  44175. globalPosition = this.position;
  44176. }
  44177. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  44178. this._oldPosition.addInPlace(this.ellipsoidOffset);
  44179. if (!this._collider) {
  44180. this._collider = new BABYLON.Collider();
  44181. }
  44182. this._collider._radius = this.ellipsoid;
  44183. this._collider.collisionMask = this._collisionMask;
  44184. //no need for clone, as long as gravity is not on.
  44185. var actualDisplacement = displacement;
  44186. //add gravity to the direction to prevent the dual-collision checking
  44187. if (this.applyGravity) {
  44188. //this prevents mending with cameraDirection, a global variable of the free camera class.
  44189. actualDisplacement = displacement.add(this.getScene().gravity);
  44190. }
  44191. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44192. };
  44193. FreeCamera.prototype._checkInputs = function () {
  44194. if (!this._localDirection) {
  44195. this._localDirection = BABYLON.Vector3.Zero();
  44196. this._transformedDirection = BABYLON.Vector3.Zero();
  44197. }
  44198. this.inputs.checkInputs();
  44199. _super.prototype._checkInputs.call(this);
  44200. };
  44201. FreeCamera.prototype._decideIfNeedsToMove = function () {
  44202. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  44203. };
  44204. FreeCamera.prototype._updatePosition = function () {
  44205. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  44206. this._collideWithWorld(this.cameraDirection);
  44207. }
  44208. else {
  44209. _super.prototype._updatePosition.call(this);
  44210. }
  44211. };
  44212. FreeCamera.prototype.dispose = function () {
  44213. this.inputs.clear();
  44214. _super.prototype.dispose.call(this);
  44215. };
  44216. FreeCamera.prototype.getClassName = function () {
  44217. return "FreeCamera";
  44218. };
  44219. __decorate([
  44220. BABYLON.serializeAsVector3()
  44221. ], FreeCamera.prototype, "ellipsoid", void 0);
  44222. __decorate([
  44223. BABYLON.serializeAsVector3()
  44224. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  44225. __decorate([
  44226. BABYLON.serialize()
  44227. ], FreeCamera.prototype, "checkCollisions", void 0);
  44228. __decorate([
  44229. BABYLON.serialize()
  44230. ], FreeCamera.prototype, "applyGravity", void 0);
  44231. return FreeCamera;
  44232. }(BABYLON.TargetCamera));
  44233. BABYLON.FreeCamera = FreeCamera;
  44234. })(BABYLON || (BABYLON = {}));
  44235. //# sourceMappingURL=babylon.freeCamera.js.map
  44236. var BABYLON;
  44237. (function (BABYLON) {
  44238. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  44239. function ArcRotateCameraKeyboardMoveInput() {
  44240. this._keys = new Array();
  44241. this.keysUp = [38];
  44242. this.keysDown = [40];
  44243. this.keysLeft = [37];
  44244. this.keysRight = [39];
  44245. this.keysReset = [220];
  44246. this.panningSensibility = 50.0;
  44247. this.zoomingSensibility = 25.0;
  44248. this.useAltToZoom = true;
  44249. }
  44250. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  44251. var _this = this;
  44252. if (this._onCanvasBlurObserver) {
  44253. return;
  44254. }
  44255. this._scene = this.camera.getScene();
  44256. this._engine = this._scene.getEngine();
  44257. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44258. _this._keys = [];
  44259. });
  44260. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44261. var evt = info.event;
  44262. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44263. _this._ctrlPressed = evt.ctrlKey;
  44264. _this._altPressed = evt.altKey;
  44265. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44266. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44267. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44268. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44269. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44270. var index = _this._keys.indexOf(evt.keyCode);
  44271. if (index === -1) {
  44272. _this._keys.push(evt.keyCode);
  44273. }
  44274. if (evt.preventDefault) {
  44275. if (!noPreventDefault) {
  44276. evt.preventDefault();
  44277. }
  44278. }
  44279. }
  44280. }
  44281. else {
  44282. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44283. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44284. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44285. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44286. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44287. var index = _this._keys.indexOf(evt.keyCode);
  44288. if (index >= 0) {
  44289. _this._keys.splice(index, 1);
  44290. }
  44291. if (evt.preventDefault) {
  44292. if (!noPreventDefault) {
  44293. evt.preventDefault();
  44294. }
  44295. }
  44296. }
  44297. }
  44298. });
  44299. };
  44300. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44301. if (this._scene) {
  44302. if (this._onKeyboardObserver) {
  44303. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44304. }
  44305. if (this._onCanvasBlurObserver) {
  44306. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44307. }
  44308. this._onKeyboardObserver = null;
  44309. this._onCanvasBlurObserver = null;
  44310. }
  44311. this._keys = [];
  44312. };
  44313. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44314. if (this._onKeyboardObserver) {
  44315. var camera = this.camera;
  44316. for (var index = 0; index < this._keys.length; index++) {
  44317. var keyCode = this._keys[index];
  44318. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44319. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44320. camera.inertialPanningX -= 1 / this.panningSensibility;
  44321. }
  44322. else {
  44323. camera.inertialAlphaOffset -= 0.01;
  44324. }
  44325. }
  44326. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44327. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44328. camera.inertialPanningY += 1 / this.panningSensibility;
  44329. }
  44330. else if (this._altPressed && this.useAltToZoom) {
  44331. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  44332. }
  44333. else {
  44334. camera.inertialBetaOffset -= 0.01;
  44335. }
  44336. }
  44337. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44338. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44339. camera.inertialPanningX += 1 / this.panningSensibility;
  44340. }
  44341. else {
  44342. camera.inertialAlphaOffset += 0.01;
  44343. }
  44344. }
  44345. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44346. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44347. camera.inertialPanningY -= 1 / this.panningSensibility;
  44348. }
  44349. else if (this._altPressed && this.useAltToZoom) {
  44350. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  44351. }
  44352. else {
  44353. camera.inertialBetaOffset += 0.01;
  44354. }
  44355. }
  44356. else if (this.keysReset.indexOf(keyCode) !== -1) {
  44357. camera.restoreState();
  44358. }
  44359. }
  44360. }
  44361. };
  44362. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  44363. return "ArcRotateCameraKeyboardMoveInput";
  44364. };
  44365. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44366. return "keyboard";
  44367. };
  44368. __decorate([
  44369. BABYLON.serialize()
  44370. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44371. __decorate([
  44372. BABYLON.serialize()
  44373. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44374. __decorate([
  44375. BABYLON.serialize()
  44376. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44377. __decorate([
  44378. BABYLON.serialize()
  44379. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44380. __decorate([
  44381. BABYLON.serialize()
  44382. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  44383. __decorate([
  44384. BABYLON.serialize()
  44385. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  44386. __decorate([
  44387. BABYLON.serialize()
  44388. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  44389. __decorate([
  44390. BABYLON.serialize()
  44391. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  44392. return ArcRotateCameraKeyboardMoveInput;
  44393. }());
  44394. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  44395. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  44396. })(BABYLON || (BABYLON = {}));
  44397. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  44398. var BABYLON;
  44399. (function (BABYLON) {
  44400. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  44401. function ArcRotateCameraMouseWheelInput() {
  44402. this.wheelPrecision = 3.0;
  44403. /**
  44404. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  44405. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  44406. */
  44407. this.wheelDeltaPercentage = 0;
  44408. }
  44409. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  44410. var _this = this;
  44411. this._wheel = function (p, s) {
  44412. //sanity check - this should be a PointerWheel event.
  44413. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  44414. return;
  44415. var event = p.event;
  44416. var delta = 0;
  44417. if (event.wheelDelta) {
  44418. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  44419. }
  44420. else if (event.detail) {
  44421. delta = -event.detail / _this.wheelPrecision;
  44422. }
  44423. if (delta)
  44424. _this.camera.inertialRadiusOffset += delta;
  44425. if (event.preventDefault) {
  44426. if (!noPreventDefault) {
  44427. event.preventDefault();
  44428. }
  44429. }
  44430. };
  44431. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  44432. };
  44433. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  44434. if (this._observer && element) {
  44435. this.camera.getScene().onPointerObservable.remove(this._observer);
  44436. this._observer = null;
  44437. this._wheel = null;
  44438. }
  44439. };
  44440. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  44441. return "ArcRotateCameraMouseWheelInput";
  44442. };
  44443. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  44444. return "mousewheel";
  44445. };
  44446. __decorate([
  44447. BABYLON.serialize()
  44448. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  44449. __decorate([
  44450. BABYLON.serialize()
  44451. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  44452. return ArcRotateCameraMouseWheelInput;
  44453. }());
  44454. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  44455. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  44456. })(BABYLON || (BABYLON = {}));
  44457. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  44458. var BABYLON;
  44459. (function (BABYLON) {
  44460. var ArcRotateCameraPointersInput = /** @class */ (function () {
  44461. function ArcRotateCameraPointersInput() {
  44462. this.buttons = [0, 1, 2];
  44463. this.angularSensibilityX = 1000.0;
  44464. this.angularSensibilityY = 1000.0;
  44465. this.pinchPrecision = 12.0;
  44466. /**
  44467. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  44468. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  44469. */
  44470. this.pinchDeltaPercentage = 0;
  44471. this.panningSensibility = 1000.0;
  44472. this.multiTouchPanning = true;
  44473. this.multiTouchPanAndZoom = true;
  44474. this._isPanClick = false;
  44475. this.pinchInwards = true;
  44476. }
  44477. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  44478. var _this = this;
  44479. var engine = this.camera.getEngine();
  44480. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  44481. var pointA = null;
  44482. var pointB = null;
  44483. var previousPinchSquaredDistance = 0;
  44484. var initialDistance = 0;
  44485. var twoFingerActivityCount = 0;
  44486. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  44487. this._pointerInput = function (p, s) {
  44488. var evt = p.event;
  44489. var isTouch = p.event.pointerType === "touch";
  44490. if (engine.isInVRExclusivePointerMode) {
  44491. return;
  44492. }
  44493. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44494. return;
  44495. }
  44496. var srcElement = (evt.srcElement || evt.target);
  44497. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44498. try {
  44499. srcElement.setPointerCapture(evt.pointerId);
  44500. }
  44501. catch (e) {
  44502. //Nothing to do with the error. Execution will continue.
  44503. }
  44504. // Manage panning with pan button click
  44505. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  44506. // manage pointers
  44507. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  44508. if (pointA === null) {
  44509. pointA = cacheSoloPointer;
  44510. }
  44511. else if (pointB === null) {
  44512. pointB = cacheSoloPointer;
  44513. }
  44514. if (!noPreventDefault) {
  44515. evt.preventDefault();
  44516. element.focus();
  44517. }
  44518. }
  44519. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  44520. _this.camera.restoreState();
  44521. }
  44522. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44523. try {
  44524. srcElement.releasePointerCapture(evt.pointerId);
  44525. }
  44526. catch (e) {
  44527. //Nothing to do with the error.
  44528. }
  44529. cacheSoloPointer = null;
  44530. previousPinchSquaredDistance = 0;
  44531. previousMultiTouchPanPosition.isPaning = false;
  44532. previousMultiTouchPanPosition.isPinching = false;
  44533. twoFingerActivityCount = 0;
  44534. initialDistance = 0;
  44535. if (!isTouch) {
  44536. pointB = null; // Mouse and pen are mono pointer
  44537. }
  44538. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  44539. //but emptying completly pointers collection is required to fix a bug on iPhone :
  44540. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  44541. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  44542. if (engine.badOS) {
  44543. pointA = pointB = null;
  44544. }
  44545. else {
  44546. //only remove the impacted pointer in case of multitouch allowing on most
  44547. //platforms switching from rotate to zoom and pan seamlessly.
  44548. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  44549. pointA = pointB;
  44550. pointB = null;
  44551. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44552. }
  44553. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  44554. pointB = null;
  44555. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44556. }
  44557. else {
  44558. pointA = pointB = null;
  44559. }
  44560. }
  44561. if (!noPreventDefault) {
  44562. evt.preventDefault();
  44563. }
  44564. }
  44565. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44566. if (!noPreventDefault) {
  44567. evt.preventDefault();
  44568. }
  44569. // One button down
  44570. if (pointA && pointB === null && cacheSoloPointer) {
  44571. if (_this.panningSensibility !== 0 &&
  44572. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  44573. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  44574. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44575. }
  44576. else {
  44577. var offsetX = evt.clientX - cacheSoloPointer.x;
  44578. var offsetY = evt.clientY - cacheSoloPointer.y;
  44579. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44580. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44581. }
  44582. cacheSoloPointer.x = evt.clientX;
  44583. cacheSoloPointer.y = evt.clientY;
  44584. }
  44585. else if (pointA && pointB) {
  44586. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44587. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44588. ed.x = evt.clientX;
  44589. ed.y = evt.clientY;
  44590. var direction = _this.pinchInwards ? 1 : -1;
  44591. var distX = pointA.x - pointB.x;
  44592. var distY = pointA.y - pointB.y;
  44593. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44594. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44595. if (previousPinchSquaredDistance === 0) {
  44596. initialDistance = pinchDistance;
  44597. previousPinchSquaredDistance = pinchSquaredDistance;
  44598. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44599. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44600. return;
  44601. }
  44602. if (_this.multiTouchPanAndZoom) {
  44603. if (_this.pinchDeltaPercentage) {
  44604. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44605. }
  44606. else {
  44607. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44608. (_this.pinchPrecision *
  44609. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44610. direction);
  44611. }
  44612. if (_this.panningSensibility !== 0) {
  44613. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44614. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44615. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44616. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44617. previousMultiTouchPanPosition.x = pointersCenterX;
  44618. previousMultiTouchPanPosition.y = pointersCenterY;
  44619. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44620. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44621. }
  44622. }
  44623. else {
  44624. twoFingerActivityCount++;
  44625. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44626. if (_this.pinchDeltaPercentage) {
  44627. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44628. }
  44629. else {
  44630. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44631. (_this.pinchPrecision *
  44632. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44633. direction);
  44634. }
  44635. previousMultiTouchPanPosition.isPaning = false;
  44636. previousMultiTouchPanPosition.isPinching = true;
  44637. }
  44638. else {
  44639. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44640. if (!previousMultiTouchPanPosition.isPaning) {
  44641. previousMultiTouchPanPosition.isPaning = true;
  44642. previousMultiTouchPanPosition.isPinching = false;
  44643. previousMultiTouchPanPosition.x = ed.x;
  44644. previousMultiTouchPanPosition.y = ed.y;
  44645. return;
  44646. }
  44647. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44648. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44649. }
  44650. }
  44651. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44652. previousMultiTouchPanPosition.x = ed.x;
  44653. previousMultiTouchPanPosition.y = ed.y;
  44654. }
  44655. }
  44656. previousPinchSquaredDistance = pinchSquaredDistance;
  44657. }
  44658. }
  44659. };
  44660. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44661. this._onContextMenu = function (evt) {
  44662. evt.preventDefault();
  44663. };
  44664. if (!this.camera._useCtrlForPanning) {
  44665. element.addEventListener("contextmenu", this._onContextMenu, false);
  44666. }
  44667. this._onLostFocus = function () {
  44668. //this._keys = [];
  44669. pointA = pointB = null;
  44670. previousPinchSquaredDistance = 0;
  44671. previousMultiTouchPanPosition.isPaning = false;
  44672. previousMultiTouchPanPosition.isPinching = false;
  44673. twoFingerActivityCount = 0;
  44674. cacheSoloPointer = null;
  44675. initialDistance = 0;
  44676. };
  44677. this._onMouseMove = function (evt) {
  44678. if (!engine.isPointerLock) {
  44679. return;
  44680. }
  44681. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44682. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44683. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44684. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44685. if (!noPreventDefault) {
  44686. evt.preventDefault();
  44687. }
  44688. };
  44689. this._onGestureStart = function (e) {
  44690. if (window.MSGesture === undefined) {
  44691. return;
  44692. }
  44693. if (!_this._MSGestureHandler) {
  44694. _this._MSGestureHandler = new MSGesture();
  44695. _this._MSGestureHandler.target = element;
  44696. }
  44697. _this._MSGestureHandler.addPointer(e.pointerId);
  44698. };
  44699. this._onGesture = function (e) {
  44700. _this.camera.radius *= e.scale;
  44701. if (e.preventDefault) {
  44702. if (!noPreventDefault) {
  44703. e.stopPropagation();
  44704. e.preventDefault();
  44705. }
  44706. }
  44707. };
  44708. element.addEventListener("mousemove", this._onMouseMove, false);
  44709. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44710. element.addEventListener("MSGestureChange", this._onGesture, false);
  44711. BABYLON.Tools.RegisterTopRootEvents([
  44712. { name: "blur", handler: this._onLostFocus }
  44713. ]);
  44714. };
  44715. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44716. if (this._onLostFocus) {
  44717. BABYLON.Tools.UnregisterTopRootEvents([
  44718. { name: "blur", handler: this._onLostFocus }
  44719. ]);
  44720. }
  44721. if (element && this._observer) {
  44722. this.camera.getScene().onPointerObservable.remove(this._observer);
  44723. this._observer = null;
  44724. if (this._onContextMenu) {
  44725. element.removeEventListener("contextmenu", this._onContextMenu);
  44726. }
  44727. if (this._onMouseMove) {
  44728. element.removeEventListener("mousemove", this._onMouseMove);
  44729. }
  44730. if (this._onGestureStart) {
  44731. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44732. }
  44733. if (this._onGesture) {
  44734. element.removeEventListener("MSGestureChange", this._onGesture);
  44735. }
  44736. this._isPanClick = false;
  44737. this.pinchInwards = true;
  44738. this._onMouseMove = null;
  44739. this._onGestureStart = null;
  44740. this._onGesture = null;
  44741. this._MSGestureHandler = null;
  44742. this._onLostFocus = null;
  44743. this._onContextMenu = null;
  44744. }
  44745. };
  44746. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44747. return "ArcRotateCameraPointersInput";
  44748. };
  44749. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44750. return "pointers";
  44751. };
  44752. __decorate([
  44753. BABYLON.serialize()
  44754. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44755. __decorate([
  44756. BABYLON.serialize()
  44757. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  44758. __decorate([
  44759. BABYLON.serialize()
  44760. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  44761. __decorate([
  44762. BABYLON.serialize()
  44763. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  44764. __decorate([
  44765. BABYLON.serialize()
  44766. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  44767. __decorate([
  44768. BABYLON.serialize()
  44769. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  44770. __decorate([
  44771. BABYLON.serialize()
  44772. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  44773. __decorate([
  44774. BABYLON.serialize()
  44775. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  44776. return ArcRotateCameraPointersInput;
  44777. }());
  44778. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  44779. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  44780. })(BABYLON || (BABYLON = {}));
  44781. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  44782. var BABYLON;
  44783. (function (BABYLON) {
  44784. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  44785. __extends(ArcRotateCameraInputsManager, _super);
  44786. function ArcRotateCameraInputsManager(camera) {
  44787. return _super.call(this, camera) || this;
  44788. }
  44789. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  44790. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  44791. return this;
  44792. };
  44793. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  44794. this.add(new BABYLON.ArcRotateCameraPointersInput());
  44795. return this;
  44796. };
  44797. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  44798. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  44799. return this;
  44800. };
  44801. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  44802. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  44803. return this;
  44804. };
  44805. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  44806. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  44807. return this;
  44808. };
  44809. return ArcRotateCameraInputsManager;
  44810. }(BABYLON.CameraInputsManager));
  44811. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  44812. })(BABYLON || (BABYLON = {}));
  44813. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  44814. var BABYLON;
  44815. (function (BABYLON) {
  44816. var ArcRotateCamera = /** @class */ (function (_super) {
  44817. __extends(ArcRotateCamera, _super);
  44818. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  44819. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  44820. _this.inertialAlphaOffset = 0;
  44821. _this.inertialBetaOffset = 0;
  44822. _this.inertialRadiusOffset = 0;
  44823. _this.lowerAlphaLimit = null;
  44824. _this.upperAlphaLimit = null;
  44825. _this.lowerBetaLimit = 0.01;
  44826. _this.upperBetaLimit = Math.PI;
  44827. _this.lowerRadiusLimit = null;
  44828. _this.upperRadiusLimit = null;
  44829. _this.inertialPanningX = 0;
  44830. _this.inertialPanningY = 0;
  44831. _this.pinchToPanMaxDistance = 20;
  44832. _this.panningDistanceLimit = null;
  44833. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  44834. _this.panningInertia = 0.9;
  44835. //-- end properties for backward compatibility for inputs
  44836. _this.zoomOnFactor = 1;
  44837. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  44838. _this.allowUpsideDown = true;
  44839. _this._viewMatrix = new BABYLON.Matrix();
  44840. // Panning
  44841. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  44842. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  44843. _this.checkCollisions = false;
  44844. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44845. _this._previousPosition = BABYLON.Vector3.Zero();
  44846. _this._collisionVelocity = BABYLON.Vector3.Zero();
  44847. _this._newPosition = BABYLON.Vector3.Zero();
  44848. _this._computationVector = BABYLON.Vector3.Zero();
  44849. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44850. if (collidedMesh === void 0) { collidedMesh = null; }
  44851. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  44852. newPosition.multiplyInPlace(_this._collider._radius);
  44853. }
  44854. if (!collidedMesh) {
  44855. _this._previousPosition.copyFrom(_this.position);
  44856. }
  44857. else {
  44858. _this.setPosition(newPosition);
  44859. if (_this.onCollide) {
  44860. _this.onCollide(collidedMesh);
  44861. }
  44862. }
  44863. // Recompute because of constraints
  44864. var cosa = Math.cos(_this.alpha);
  44865. var sina = Math.sin(_this.alpha);
  44866. var cosb = Math.cos(_this.beta);
  44867. var sinb = Math.sin(_this.beta);
  44868. if (sinb === 0) {
  44869. sinb = 0.0001;
  44870. }
  44871. var target = _this._getTargetPosition();
  44872. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  44873. target.addToRef(_this._computationVector, _this._newPosition);
  44874. _this.position.copyFrom(_this._newPosition);
  44875. var up = _this.upVector;
  44876. if (_this.allowUpsideDown && _this.beta < 0) {
  44877. up = up.clone();
  44878. up = up.negate();
  44879. }
  44880. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  44881. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  44882. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  44883. _this._collisionTriggered = false;
  44884. };
  44885. _this._target = BABYLON.Vector3.Zero();
  44886. if (target) {
  44887. _this.setTarget(target);
  44888. }
  44889. _this.alpha = alpha;
  44890. _this.beta = beta;
  44891. _this.radius = radius;
  44892. _this.getViewMatrix();
  44893. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  44894. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  44895. return _this;
  44896. }
  44897. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  44898. get: function () {
  44899. return this._target;
  44900. },
  44901. set: function (value) {
  44902. this.setTarget(value);
  44903. },
  44904. enumerable: true,
  44905. configurable: true
  44906. });
  44907. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  44908. //-- begin properties for backward compatibility for inputs
  44909. get: function () {
  44910. var pointers = this.inputs.attached["pointers"];
  44911. if (pointers)
  44912. return pointers.angularSensibilityX;
  44913. return 0;
  44914. },
  44915. set: function (value) {
  44916. var pointers = this.inputs.attached["pointers"];
  44917. if (pointers) {
  44918. pointers.angularSensibilityX = value;
  44919. }
  44920. },
  44921. enumerable: true,
  44922. configurable: true
  44923. });
  44924. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  44925. get: function () {
  44926. var pointers = this.inputs.attached["pointers"];
  44927. if (pointers)
  44928. return pointers.angularSensibilityY;
  44929. return 0;
  44930. },
  44931. set: function (value) {
  44932. var pointers = this.inputs.attached["pointers"];
  44933. if (pointers) {
  44934. pointers.angularSensibilityY = value;
  44935. }
  44936. },
  44937. enumerable: true,
  44938. configurable: true
  44939. });
  44940. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  44941. get: function () {
  44942. var pointers = this.inputs.attached["pointers"];
  44943. if (pointers)
  44944. return pointers.pinchPrecision;
  44945. return 0;
  44946. },
  44947. set: function (value) {
  44948. var pointers = this.inputs.attached["pointers"];
  44949. if (pointers) {
  44950. pointers.pinchPrecision = value;
  44951. }
  44952. },
  44953. enumerable: true,
  44954. configurable: true
  44955. });
  44956. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  44957. get: function () {
  44958. var pointers = this.inputs.attached["pointers"];
  44959. if (pointers)
  44960. return pointers.pinchDeltaPercentage;
  44961. return 0;
  44962. },
  44963. set: function (value) {
  44964. var pointers = this.inputs.attached["pointers"];
  44965. if (pointers) {
  44966. pointers.pinchDeltaPercentage = value;
  44967. }
  44968. },
  44969. enumerable: true,
  44970. configurable: true
  44971. });
  44972. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  44973. get: function () {
  44974. var pointers = this.inputs.attached["pointers"];
  44975. if (pointers)
  44976. return pointers.panningSensibility;
  44977. return 0;
  44978. },
  44979. set: function (value) {
  44980. var pointers = this.inputs.attached["pointers"];
  44981. if (pointers) {
  44982. pointers.panningSensibility = value;
  44983. }
  44984. },
  44985. enumerable: true,
  44986. configurable: true
  44987. });
  44988. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  44989. get: function () {
  44990. var keyboard = this.inputs.attached["keyboard"];
  44991. if (keyboard)
  44992. return keyboard.keysUp;
  44993. return [];
  44994. },
  44995. set: function (value) {
  44996. var keyboard = this.inputs.attached["keyboard"];
  44997. if (keyboard)
  44998. keyboard.keysUp = value;
  44999. },
  45000. enumerable: true,
  45001. configurable: true
  45002. });
  45003. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  45004. get: function () {
  45005. var keyboard = this.inputs.attached["keyboard"];
  45006. if (keyboard)
  45007. return keyboard.keysDown;
  45008. return [];
  45009. },
  45010. set: function (value) {
  45011. var keyboard = this.inputs.attached["keyboard"];
  45012. if (keyboard)
  45013. keyboard.keysDown = value;
  45014. },
  45015. enumerable: true,
  45016. configurable: true
  45017. });
  45018. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  45019. get: function () {
  45020. var keyboard = this.inputs.attached["keyboard"];
  45021. if (keyboard)
  45022. return keyboard.keysLeft;
  45023. return [];
  45024. },
  45025. set: function (value) {
  45026. var keyboard = this.inputs.attached["keyboard"];
  45027. if (keyboard)
  45028. keyboard.keysLeft = value;
  45029. },
  45030. enumerable: true,
  45031. configurable: true
  45032. });
  45033. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  45034. get: function () {
  45035. var keyboard = this.inputs.attached["keyboard"];
  45036. if (keyboard)
  45037. return keyboard.keysRight;
  45038. return [];
  45039. },
  45040. set: function (value) {
  45041. var keyboard = this.inputs.attached["keyboard"];
  45042. if (keyboard)
  45043. keyboard.keysRight = value;
  45044. },
  45045. enumerable: true,
  45046. configurable: true
  45047. });
  45048. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  45049. get: function () {
  45050. var mousewheel = this.inputs.attached["mousewheel"];
  45051. if (mousewheel)
  45052. return mousewheel.wheelPrecision;
  45053. return 0;
  45054. },
  45055. set: function (value) {
  45056. var mousewheel = this.inputs.attached["mousewheel"];
  45057. if (mousewheel)
  45058. mousewheel.wheelPrecision = value;
  45059. },
  45060. enumerable: true,
  45061. configurable: true
  45062. });
  45063. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  45064. get: function () {
  45065. var mousewheel = this.inputs.attached["mousewheel"];
  45066. if (mousewheel)
  45067. return mousewheel.wheelDeltaPercentage;
  45068. return 0;
  45069. },
  45070. set: function (value) {
  45071. var mousewheel = this.inputs.attached["mousewheel"];
  45072. if (mousewheel)
  45073. mousewheel.wheelDeltaPercentage = value;
  45074. },
  45075. enumerable: true,
  45076. configurable: true
  45077. });
  45078. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  45079. get: function () {
  45080. return this._bouncingBehavior;
  45081. },
  45082. enumerable: true,
  45083. configurable: true
  45084. });
  45085. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  45086. get: function () {
  45087. return this._bouncingBehavior != null;
  45088. },
  45089. set: function (value) {
  45090. if (value === this.useBouncingBehavior) {
  45091. return;
  45092. }
  45093. if (value) {
  45094. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  45095. this.addBehavior(this._bouncingBehavior);
  45096. }
  45097. else if (this._bouncingBehavior) {
  45098. this.removeBehavior(this._bouncingBehavior);
  45099. this._bouncingBehavior = null;
  45100. }
  45101. },
  45102. enumerable: true,
  45103. configurable: true
  45104. });
  45105. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  45106. get: function () {
  45107. return this._framingBehavior;
  45108. },
  45109. enumerable: true,
  45110. configurable: true
  45111. });
  45112. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  45113. get: function () {
  45114. return this._framingBehavior != null;
  45115. },
  45116. set: function (value) {
  45117. if (value === this.useFramingBehavior) {
  45118. return;
  45119. }
  45120. if (value) {
  45121. this._framingBehavior = new BABYLON.FramingBehavior();
  45122. this.addBehavior(this._framingBehavior);
  45123. }
  45124. else if (this._framingBehavior) {
  45125. this.removeBehavior(this._framingBehavior);
  45126. this._framingBehavior = null;
  45127. }
  45128. },
  45129. enumerable: true,
  45130. configurable: true
  45131. });
  45132. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  45133. get: function () {
  45134. return this._autoRotationBehavior;
  45135. },
  45136. enumerable: true,
  45137. configurable: true
  45138. });
  45139. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  45140. get: function () {
  45141. return this._autoRotationBehavior != null;
  45142. },
  45143. set: function (value) {
  45144. if (value === this.useAutoRotationBehavior) {
  45145. return;
  45146. }
  45147. if (value) {
  45148. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  45149. this.addBehavior(this._autoRotationBehavior);
  45150. }
  45151. else if (this._autoRotationBehavior) {
  45152. this.removeBehavior(this._autoRotationBehavior);
  45153. this._autoRotationBehavior = null;
  45154. }
  45155. },
  45156. enumerable: true,
  45157. configurable: true
  45158. });
  45159. // Cache
  45160. ArcRotateCamera.prototype._initCache = function () {
  45161. _super.prototype._initCache.call(this);
  45162. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45163. this._cache.alpha = undefined;
  45164. this._cache.beta = undefined;
  45165. this._cache.radius = undefined;
  45166. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  45167. };
  45168. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  45169. if (!ignoreParentClass) {
  45170. _super.prototype._updateCache.call(this);
  45171. }
  45172. this._cache._target.copyFrom(this._getTargetPosition());
  45173. this._cache.alpha = this.alpha;
  45174. this._cache.beta = this.beta;
  45175. this._cache.radius = this.radius;
  45176. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  45177. };
  45178. ArcRotateCamera.prototype._getTargetPosition = function () {
  45179. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  45180. var pos = this._targetHost.getAbsolutePosition();
  45181. if (this._targetBoundingCenter) {
  45182. pos.addToRef(this._targetBoundingCenter, this._target);
  45183. }
  45184. else {
  45185. this._target.copyFrom(pos);
  45186. }
  45187. }
  45188. var lockedTargetPosition = this._getLockedTargetPosition();
  45189. if (lockedTargetPosition) {
  45190. return lockedTargetPosition;
  45191. }
  45192. return this._target;
  45193. };
  45194. ArcRotateCamera.prototype.storeState = function () {
  45195. this._storedAlpha = this.alpha;
  45196. this._storedBeta = this.beta;
  45197. this._storedRadius = this.radius;
  45198. this._storedTarget = this._getTargetPosition().clone();
  45199. return _super.prototype.storeState.call(this);
  45200. };
  45201. /**
  45202. * Restored camera state. You must call storeState() first
  45203. */
  45204. ArcRotateCamera.prototype._restoreStateValues = function () {
  45205. if (!_super.prototype._restoreStateValues.call(this)) {
  45206. return false;
  45207. }
  45208. this.alpha = this._storedAlpha;
  45209. this.beta = this._storedBeta;
  45210. this.radius = this._storedRadius;
  45211. this.setTarget(this._storedTarget.clone());
  45212. this.inertialAlphaOffset = 0;
  45213. this.inertialBetaOffset = 0;
  45214. this.inertialRadiusOffset = 0;
  45215. this.inertialPanningX = 0;
  45216. this.inertialPanningY = 0;
  45217. return true;
  45218. };
  45219. // Synchronized
  45220. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  45221. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  45222. return false;
  45223. return this._cache._target.equals(this._getTargetPosition())
  45224. && this._cache.alpha === this.alpha
  45225. && this._cache.beta === this.beta
  45226. && this._cache.radius === this.radius
  45227. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  45228. };
  45229. // Methods
  45230. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  45231. var _this = this;
  45232. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  45233. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  45234. this._useCtrlForPanning = useCtrlForPanning;
  45235. this._panningMouseButton = panningMouseButton;
  45236. this.inputs.attachElement(element, noPreventDefault);
  45237. this._reset = function () {
  45238. _this.inertialAlphaOffset = 0;
  45239. _this.inertialBetaOffset = 0;
  45240. _this.inertialRadiusOffset = 0;
  45241. _this.inertialPanningX = 0;
  45242. _this.inertialPanningY = 0;
  45243. };
  45244. };
  45245. ArcRotateCamera.prototype.detachControl = function (element) {
  45246. this.inputs.detachElement(element);
  45247. if (this._reset) {
  45248. this._reset();
  45249. }
  45250. };
  45251. ArcRotateCamera.prototype._checkInputs = function () {
  45252. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  45253. if (this._collisionTriggered) {
  45254. return;
  45255. }
  45256. this.inputs.checkInputs();
  45257. // Inertia
  45258. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  45259. if (this.getScene().useRightHandedSystem) {
  45260. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45261. }
  45262. else {
  45263. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45264. }
  45265. this.beta += this.inertialBetaOffset;
  45266. this.radius -= this.inertialRadiusOffset;
  45267. this.inertialAlphaOffset *= this.inertia;
  45268. this.inertialBetaOffset *= this.inertia;
  45269. this.inertialRadiusOffset *= this.inertia;
  45270. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  45271. this.inertialAlphaOffset = 0;
  45272. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  45273. this.inertialBetaOffset = 0;
  45274. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  45275. this.inertialRadiusOffset = 0;
  45276. }
  45277. // Panning inertia
  45278. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  45279. if (!this._localDirection) {
  45280. this._localDirection = BABYLON.Vector3.Zero();
  45281. this._transformedDirection = BABYLON.Vector3.Zero();
  45282. }
  45283. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  45284. this._localDirection.multiplyInPlace(this.panningAxis);
  45285. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  45286. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  45287. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  45288. if (!this.panningAxis.y) {
  45289. this._transformedDirection.y = 0;
  45290. }
  45291. if (!this._targetHost) {
  45292. if (this.panningDistanceLimit) {
  45293. this._transformedDirection.addInPlace(this._target);
  45294. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  45295. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  45296. this._target.copyFrom(this._transformedDirection);
  45297. }
  45298. }
  45299. else {
  45300. this._target.addInPlace(this._transformedDirection);
  45301. }
  45302. }
  45303. this.inertialPanningX *= this.panningInertia;
  45304. this.inertialPanningY *= this.panningInertia;
  45305. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  45306. this.inertialPanningX = 0;
  45307. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  45308. this.inertialPanningY = 0;
  45309. }
  45310. // Limits
  45311. this._checkLimits();
  45312. _super.prototype._checkInputs.call(this);
  45313. };
  45314. ArcRotateCamera.prototype._checkLimits = function () {
  45315. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  45316. if (this.allowUpsideDown && this.beta > Math.PI) {
  45317. this.beta = this.beta - (2 * Math.PI);
  45318. }
  45319. }
  45320. else {
  45321. if (this.beta < this.lowerBetaLimit) {
  45322. this.beta = this.lowerBetaLimit;
  45323. }
  45324. }
  45325. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  45326. if (this.allowUpsideDown && this.beta < -Math.PI) {
  45327. this.beta = this.beta + (2 * Math.PI);
  45328. }
  45329. }
  45330. else {
  45331. if (this.beta > this.upperBetaLimit) {
  45332. this.beta = this.upperBetaLimit;
  45333. }
  45334. }
  45335. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  45336. this.alpha = this.lowerAlphaLimit;
  45337. }
  45338. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  45339. this.alpha = this.upperAlphaLimit;
  45340. }
  45341. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  45342. this.radius = this.lowerRadiusLimit;
  45343. }
  45344. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  45345. this.radius = this.upperRadiusLimit;
  45346. }
  45347. };
  45348. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  45349. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  45350. this.radius = this._computationVector.length();
  45351. if (this.radius === 0) {
  45352. this.radius = 0.0001; // Just to avoid division by zero
  45353. }
  45354. // Alpha
  45355. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  45356. if (this._computationVector.z < 0) {
  45357. this.alpha = 2 * Math.PI - this.alpha;
  45358. }
  45359. // Beta
  45360. this.beta = Math.acos(this._computationVector.y / this.radius);
  45361. this._checkLimits();
  45362. };
  45363. ArcRotateCamera.prototype.setPosition = function (position) {
  45364. if (this.position.equals(position)) {
  45365. return;
  45366. }
  45367. this.position.copyFrom(position);
  45368. this.rebuildAnglesAndRadius();
  45369. };
  45370. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  45371. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  45372. if (allowSamePosition === void 0) { allowSamePosition = false; }
  45373. if (target.getBoundingInfo) {
  45374. if (toBoundingCenter) {
  45375. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  45376. }
  45377. else {
  45378. this._targetBoundingCenter = null;
  45379. }
  45380. this._targetHost = target;
  45381. this._target = this._getTargetPosition();
  45382. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  45383. }
  45384. else {
  45385. var newTarget = target;
  45386. var currentTarget = this._getTargetPosition();
  45387. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  45388. return;
  45389. }
  45390. this._targetHost = null;
  45391. this._target = newTarget;
  45392. this._targetBoundingCenter = null;
  45393. this.onMeshTargetChangedObservable.notifyObservers(null);
  45394. }
  45395. this.rebuildAnglesAndRadius();
  45396. };
  45397. ArcRotateCamera.prototype._getViewMatrix = function () {
  45398. // Compute
  45399. var cosa = Math.cos(this.alpha);
  45400. var sina = Math.sin(this.alpha);
  45401. var cosb = Math.cos(this.beta);
  45402. var sinb = Math.sin(this.beta);
  45403. if (sinb === 0) {
  45404. sinb = 0.0001;
  45405. }
  45406. var target = this._getTargetPosition();
  45407. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  45408. target.addToRef(this._computationVector, this._newPosition);
  45409. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  45410. if (!this._collider) {
  45411. this._collider = new BABYLON.Collider();
  45412. }
  45413. this._collider._radius = this.collisionRadius;
  45414. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  45415. this._collisionTriggered = true;
  45416. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  45417. }
  45418. else {
  45419. this.position.copyFrom(this._newPosition);
  45420. var up = this.upVector;
  45421. if (this.allowUpsideDown && sinb < 0) {
  45422. up = up.clone();
  45423. up = up.negate();
  45424. }
  45425. if (this.getScene().useRightHandedSystem) {
  45426. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  45427. }
  45428. else {
  45429. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  45430. }
  45431. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  45432. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  45433. }
  45434. this._currentTarget = target;
  45435. return this._viewMatrix;
  45436. };
  45437. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  45438. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45439. meshes = meshes || this.getScene().meshes;
  45440. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  45441. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  45442. this.radius = distance * this.zoomOnFactor;
  45443. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  45444. };
  45445. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  45446. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45447. var meshesOrMinMaxVector;
  45448. var distance;
  45449. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  45450. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  45451. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  45452. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  45453. }
  45454. else {
  45455. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  45456. meshesOrMinMaxVector = minMaxVectorAndDistance;
  45457. distance = minMaxVectorAndDistance.distance;
  45458. }
  45459. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  45460. if (!doNotUpdateMaxZ) {
  45461. this.maxZ = distance * 2;
  45462. }
  45463. };
  45464. /**
  45465. * @override
  45466. * Override Camera.createRigCamera
  45467. */
  45468. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  45469. var alphaShift = 0;
  45470. switch (this.cameraRigMode) {
  45471. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45472. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45473. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45474. case BABYLON.Camera.RIG_MODE_VR:
  45475. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  45476. break;
  45477. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45478. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  45479. break;
  45480. }
  45481. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  45482. rigCam._cameraRigParams = {};
  45483. return rigCam;
  45484. };
  45485. /**
  45486. * @override
  45487. * Override Camera._updateRigCameras
  45488. */
  45489. ArcRotateCamera.prototype._updateRigCameras = function () {
  45490. var camLeft = this._rigCameras[0];
  45491. var camRight = this._rigCameras[1];
  45492. camLeft.beta = camRight.beta = this.beta;
  45493. camLeft.radius = camRight.radius = this.radius;
  45494. switch (this.cameraRigMode) {
  45495. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45496. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45497. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45498. case BABYLON.Camera.RIG_MODE_VR:
  45499. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45500. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45501. break;
  45502. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45503. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45504. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45505. break;
  45506. }
  45507. _super.prototype._updateRigCameras.call(this);
  45508. };
  45509. ArcRotateCamera.prototype.dispose = function () {
  45510. this.inputs.clear();
  45511. _super.prototype.dispose.call(this);
  45512. };
  45513. ArcRotateCamera.prototype.getClassName = function () {
  45514. return "ArcRotateCamera";
  45515. };
  45516. __decorate([
  45517. BABYLON.serialize()
  45518. ], ArcRotateCamera.prototype, "alpha", void 0);
  45519. __decorate([
  45520. BABYLON.serialize()
  45521. ], ArcRotateCamera.prototype, "beta", void 0);
  45522. __decorate([
  45523. BABYLON.serialize()
  45524. ], ArcRotateCamera.prototype, "radius", void 0);
  45525. __decorate([
  45526. BABYLON.serializeAsVector3("target")
  45527. ], ArcRotateCamera.prototype, "_target", void 0);
  45528. __decorate([
  45529. BABYLON.serialize()
  45530. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  45531. __decorate([
  45532. BABYLON.serialize()
  45533. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  45534. __decorate([
  45535. BABYLON.serialize()
  45536. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  45537. __decorate([
  45538. BABYLON.serialize()
  45539. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  45540. __decorate([
  45541. BABYLON.serialize()
  45542. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  45543. __decorate([
  45544. BABYLON.serialize()
  45545. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  45546. __decorate([
  45547. BABYLON.serialize()
  45548. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  45549. __decorate([
  45550. BABYLON.serialize()
  45551. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  45552. __decorate([
  45553. BABYLON.serialize()
  45554. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  45555. __decorate([
  45556. BABYLON.serialize()
  45557. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  45558. __decorate([
  45559. BABYLON.serialize()
  45560. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  45561. __decorate([
  45562. BABYLON.serialize()
  45563. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  45564. __decorate([
  45565. BABYLON.serialize()
  45566. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  45567. __decorate([
  45568. BABYLON.serializeAsVector3()
  45569. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  45570. __decorate([
  45571. BABYLON.serialize()
  45572. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  45573. __decorate([
  45574. BABYLON.serialize()
  45575. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  45576. __decorate([
  45577. BABYLON.serialize()
  45578. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45579. return ArcRotateCamera;
  45580. }(BABYLON.TargetCamera));
  45581. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45582. })(BABYLON || (BABYLON = {}));
  45583. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45584. var BABYLON;
  45585. (function (BABYLON) {
  45586. /**
  45587. * The HemisphericLight simulates the ambient environment light,
  45588. * so the passed direction is the light reflection direction, not the incoming direction.
  45589. */
  45590. var HemisphericLight = /** @class */ (function (_super) {
  45591. __extends(HemisphericLight, _super);
  45592. /**
  45593. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45594. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45595. * The HemisphericLight can't cast shadows.
  45596. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45597. * @param name The friendly name of the light
  45598. * @param direction The direction of the light reflection
  45599. * @param scene The scene the light belongs to
  45600. */
  45601. function HemisphericLight(name, direction, scene) {
  45602. var _this = _super.call(this, name, scene) || this;
  45603. /**
  45604. * The groundColor is the light in the opposite direction to the one specified during creation.
  45605. * 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.
  45606. */
  45607. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45608. _this.direction = direction || BABYLON.Vector3.Up();
  45609. return _this;
  45610. }
  45611. HemisphericLight.prototype._buildUniformLayout = function () {
  45612. this._uniformBuffer.addUniform("vLightData", 4);
  45613. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45614. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45615. this._uniformBuffer.addUniform("vLightGround", 3);
  45616. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45617. this._uniformBuffer.addUniform("depthValues", 2);
  45618. this._uniformBuffer.create();
  45619. };
  45620. /**
  45621. * Returns the string "HemisphericLight".
  45622. * @return The class name
  45623. */
  45624. HemisphericLight.prototype.getClassName = function () {
  45625. return "HemisphericLight";
  45626. };
  45627. /**
  45628. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45629. * Returns the updated direction.
  45630. * @param target The target the direction should point to
  45631. * @return The computed direction
  45632. */
  45633. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45634. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45635. return this.direction;
  45636. };
  45637. /**
  45638. * Returns the shadow generator associated to the light.
  45639. * @returns Always null for hemispheric lights because it does not support shadows.
  45640. */
  45641. HemisphericLight.prototype.getShadowGenerator = function () {
  45642. return null;
  45643. };
  45644. /**
  45645. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45646. * @param effect The effect to update
  45647. * @param lightIndex The index of the light in the effect to update
  45648. * @returns The hemispheric light
  45649. */
  45650. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45651. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45652. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45653. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45654. return this;
  45655. };
  45656. /**
  45657. * @ignore internal use only.
  45658. */
  45659. HemisphericLight.prototype._getWorldMatrix = function () {
  45660. if (!this._worldMatrix) {
  45661. this._worldMatrix = BABYLON.Matrix.Identity();
  45662. }
  45663. return this._worldMatrix;
  45664. };
  45665. /**
  45666. * Returns the integer 3.
  45667. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45668. */
  45669. HemisphericLight.prototype.getTypeID = function () {
  45670. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45671. };
  45672. __decorate([
  45673. BABYLON.serializeAsColor3()
  45674. ], HemisphericLight.prototype, "groundColor", void 0);
  45675. __decorate([
  45676. BABYLON.serializeAsVector3()
  45677. ], HemisphericLight.prototype, "direction", void 0);
  45678. return HemisphericLight;
  45679. }(BABYLON.Light));
  45680. BABYLON.HemisphericLight = HemisphericLight;
  45681. })(BABYLON || (BABYLON = {}));
  45682. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45683. var BABYLON;
  45684. (function (BABYLON) {
  45685. /**
  45686. * Base implementation of @see IShadowLight
  45687. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45688. */
  45689. var ShadowLight = /** @class */ (function (_super) {
  45690. __extends(ShadowLight, _super);
  45691. function ShadowLight() {
  45692. var _this = _super !== null && _super.apply(this, arguments) || this;
  45693. _this._needProjectionMatrixCompute = true;
  45694. return _this;
  45695. }
  45696. ShadowLight.prototype._setPosition = function (value) {
  45697. this._position = value;
  45698. };
  45699. Object.defineProperty(ShadowLight.prototype, "position", {
  45700. /**
  45701. * Sets the position the shadow will be casted from. Also use as the light position for both
  45702. * point and spot lights.
  45703. */
  45704. get: function () {
  45705. return this._position;
  45706. },
  45707. /**
  45708. * Sets the position the shadow will be casted from. Also use as the light position for both
  45709. * point and spot lights.
  45710. */
  45711. set: function (value) {
  45712. this._setPosition(value);
  45713. },
  45714. enumerable: true,
  45715. configurable: true
  45716. });
  45717. ShadowLight.prototype._setDirection = function (value) {
  45718. this._direction = value;
  45719. };
  45720. Object.defineProperty(ShadowLight.prototype, "direction", {
  45721. /**
  45722. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45723. * Also use as the light direction on spot and directional lights.
  45724. */
  45725. get: function () {
  45726. return this._direction;
  45727. },
  45728. /**
  45729. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45730. * Also use as the light direction on spot and directional lights.
  45731. */
  45732. set: function (value) {
  45733. this._setDirection(value);
  45734. },
  45735. enumerable: true,
  45736. configurable: true
  45737. });
  45738. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45739. /**
  45740. * Gets the shadow projection clipping minimum z value.
  45741. */
  45742. get: function () {
  45743. return this._shadowMinZ;
  45744. },
  45745. /**
  45746. * Sets the shadow projection clipping minimum z value.
  45747. */
  45748. set: function (value) {
  45749. this._shadowMinZ = value;
  45750. this.forceProjectionMatrixCompute();
  45751. },
  45752. enumerable: true,
  45753. configurable: true
  45754. });
  45755. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  45756. /**
  45757. * Sets the shadow projection clipping maximum z value.
  45758. */
  45759. get: function () {
  45760. return this._shadowMaxZ;
  45761. },
  45762. /**
  45763. * Gets the shadow projection clipping maximum z value.
  45764. */
  45765. set: function (value) {
  45766. this._shadowMaxZ = value;
  45767. this.forceProjectionMatrixCompute();
  45768. },
  45769. enumerable: true,
  45770. configurable: true
  45771. });
  45772. /**
  45773. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  45774. * @returns true if the information has been computed, false if it does not need to (no parenting)
  45775. */
  45776. ShadowLight.prototype.computeTransformedInformation = function () {
  45777. if (this.parent && this.parent.getWorldMatrix) {
  45778. if (!this.transformedPosition) {
  45779. this.transformedPosition = BABYLON.Vector3.Zero();
  45780. }
  45781. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  45782. // In case the direction is present.
  45783. if (this.direction) {
  45784. if (!this.transformedDirection) {
  45785. this.transformedDirection = BABYLON.Vector3.Zero();
  45786. }
  45787. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  45788. }
  45789. return true;
  45790. }
  45791. return false;
  45792. };
  45793. /**
  45794. * Return the depth scale used for the shadow map.
  45795. * @returns the depth scale.
  45796. */
  45797. ShadowLight.prototype.getDepthScale = function () {
  45798. return 50.0;
  45799. };
  45800. /**
  45801. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  45802. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45803. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45804. */
  45805. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  45806. return this.transformedDirection ? this.transformedDirection : this.direction;
  45807. };
  45808. /**
  45809. * Returns the ShadowLight absolute position in the World.
  45810. * @returns the position vector in world space
  45811. */
  45812. ShadowLight.prototype.getAbsolutePosition = function () {
  45813. return this.transformedPosition ? this.transformedPosition : this.position;
  45814. };
  45815. /**
  45816. * Sets the ShadowLight direction toward the passed target.
  45817. * @param target The point tot target in local space
  45818. * @returns the updated ShadowLight direction
  45819. */
  45820. ShadowLight.prototype.setDirectionToTarget = function (target) {
  45821. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  45822. return this.direction;
  45823. };
  45824. /**
  45825. * Returns the light rotation in euler definition.
  45826. * @returns the x y z rotation in local space.
  45827. */
  45828. ShadowLight.prototype.getRotation = function () {
  45829. this.direction.normalize();
  45830. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  45831. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  45832. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  45833. };
  45834. /**
  45835. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  45836. * @returns true if a cube texture needs to be use
  45837. */
  45838. ShadowLight.prototype.needCube = function () {
  45839. return false;
  45840. };
  45841. /**
  45842. * Detects if the projection matrix requires to be recomputed this frame.
  45843. * @returns true if it requires to be recomputed otherwise, false.
  45844. */
  45845. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  45846. return this._needProjectionMatrixCompute;
  45847. };
  45848. /**
  45849. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  45850. */
  45851. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  45852. this._needProjectionMatrixCompute = true;
  45853. };
  45854. /**
  45855. * Get the world matrix of the sahdow lights.
  45856. * @ignore Internal Use Only
  45857. */
  45858. ShadowLight.prototype._getWorldMatrix = function () {
  45859. if (!this._worldMatrix) {
  45860. this._worldMatrix = BABYLON.Matrix.Identity();
  45861. }
  45862. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  45863. return this._worldMatrix;
  45864. };
  45865. /**
  45866. * Gets the minZ used for shadow according to both the scene and the light.
  45867. * @param activeCamera The camera we are returning the min for
  45868. * @returns the depth min z
  45869. */
  45870. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  45871. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  45872. };
  45873. /**
  45874. * Gets the maxZ used for shadow according to both the scene and the light.
  45875. * @param activeCamera The camera we are returning the max for
  45876. * @returns the depth max z
  45877. */
  45878. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  45879. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  45880. };
  45881. /**
  45882. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  45883. * @param matrix The materix to updated with the projection information
  45884. * @param viewMatrix The transform matrix of the light
  45885. * @param renderList The list of mesh to render in the map
  45886. * @returns The current light
  45887. */
  45888. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45889. if (this.customProjectionMatrixBuilder) {
  45890. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  45891. }
  45892. else {
  45893. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45894. }
  45895. return this;
  45896. };
  45897. __decorate([
  45898. BABYLON.serializeAsVector3()
  45899. ], ShadowLight.prototype, "position", null);
  45900. __decorate([
  45901. BABYLON.serializeAsVector3()
  45902. ], ShadowLight.prototype, "direction", null);
  45903. __decorate([
  45904. BABYLON.serialize()
  45905. ], ShadowLight.prototype, "shadowMinZ", null);
  45906. __decorate([
  45907. BABYLON.serialize()
  45908. ], ShadowLight.prototype, "shadowMaxZ", null);
  45909. return ShadowLight;
  45910. }(BABYLON.Light));
  45911. BABYLON.ShadowLight = ShadowLight;
  45912. })(BABYLON || (BABYLON = {}));
  45913. //# sourceMappingURL=babylon.shadowLight.js.map
  45914. var BABYLON;
  45915. (function (BABYLON) {
  45916. /**
  45917. * A point light is a light defined by an unique point in world space.
  45918. * The light is emitted in every direction from this point.
  45919. * A good example of a point light is a standard light bulb.
  45920. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45921. */
  45922. var PointLight = /** @class */ (function (_super) {
  45923. __extends(PointLight, _super);
  45924. /**
  45925. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  45926. * A PointLight emits the light in every direction.
  45927. * It can cast shadows.
  45928. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  45929. * ```javascript
  45930. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  45931. * ```
  45932. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45933. * @param name The light friendly name
  45934. * @param position The position of the point light in the scene
  45935. * @param scene The scene the lights belongs to
  45936. */
  45937. function PointLight(name, position, scene) {
  45938. var _this = _super.call(this, name, scene) || this;
  45939. _this._shadowAngle = Math.PI / 2;
  45940. _this.position = position;
  45941. return _this;
  45942. }
  45943. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  45944. /**
  45945. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45946. * This specifies what angle the shadow will use to be created.
  45947. *
  45948. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45949. */
  45950. get: function () {
  45951. return this._shadowAngle;
  45952. },
  45953. /**
  45954. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45955. * This specifies what angle the shadow will use to be created.
  45956. *
  45957. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45958. */
  45959. set: function (value) {
  45960. this._shadowAngle = value;
  45961. this.forceProjectionMatrixCompute();
  45962. },
  45963. enumerable: true,
  45964. configurable: true
  45965. });
  45966. Object.defineProperty(PointLight.prototype, "direction", {
  45967. /**
  45968. * Gets the direction if it has been set.
  45969. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45970. */
  45971. get: function () {
  45972. return this._direction;
  45973. },
  45974. /**
  45975. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45976. */
  45977. set: function (value) {
  45978. var previousNeedCube = this.needCube();
  45979. this._direction = value;
  45980. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  45981. this._shadowGenerator.recreateShadowMap();
  45982. }
  45983. },
  45984. enumerable: true,
  45985. configurable: true
  45986. });
  45987. /**
  45988. * Returns the string "PointLight"
  45989. * @returns the class name
  45990. */
  45991. PointLight.prototype.getClassName = function () {
  45992. return "PointLight";
  45993. };
  45994. /**
  45995. * Returns the integer 0.
  45996. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45997. */
  45998. PointLight.prototype.getTypeID = function () {
  45999. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  46000. };
  46001. /**
  46002. * Specifies wether or not the shadowmap should be a cube texture.
  46003. * @returns true if the shadowmap needs to be a cube texture.
  46004. */
  46005. PointLight.prototype.needCube = function () {
  46006. return !this.direction;
  46007. };
  46008. /**
  46009. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  46010. * @param faceIndex The index of the face we are computed the direction to generate shadow
  46011. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  46012. */
  46013. PointLight.prototype.getShadowDirection = function (faceIndex) {
  46014. if (this.direction) {
  46015. return _super.prototype.getShadowDirection.call(this, faceIndex);
  46016. }
  46017. else {
  46018. switch (faceIndex) {
  46019. case 0:
  46020. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  46021. case 1:
  46022. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  46023. case 2:
  46024. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  46025. case 3:
  46026. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  46027. case 4:
  46028. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  46029. case 5:
  46030. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  46031. }
  46032. }
  46033. return BABYLON.Vector3.Zero();
  46034. };
  46035. /**
  46036. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  46037. * - fov = PI / 2
  46038. * - aspect ratio : 1.0
  46039. * - z-near and far equal to the active camera minZ and maxZ.
  46040. * Returns the PointLight.
  46041. */
  46042. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46043. var activeCamera = this.getScene().activeCamera;
  46044. if (!activeCamera) {
  46045. return;
  46046. }
  46047. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46048. };
  46049. PointLight.prototype._buildUniformLayout = function () {
  46050. this._uniformBuffer.addUniform("vLightData", 4);
  46051. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46052. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46053. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46054. this._uniformBuffer.addUniform("depthValues", 2);
  46055. this._uniformBuffer.create();
  46056. };
  46057. /**
  46058. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  46059. * @param effect The effect to update
  46060. * @param lightIndex The index of the light in the effect to update
  46061. * @returns The point light
  46062. */
  46063. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  46064. if (this.computeTransformedInformation()) {
  46065. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  46066. return this;
  46067. }
  46068. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  46069. return this;
  46070. };
  46071. __decorate([
  46072. BABYLON.serialize()
  46073. ], PointLight.prototype, "shadowAngle", null);
  46074. return PointLight;
  46075. }(BABYLON.ShadowLight));
  46076. BABYLON.PointLight = PointLight;
  46077. })(BABYLON || (BABYLON = {}));
  46078. //# sourceMappingURL=babylon.pointLight.js.map
  46079. var BABYLON;
  46080. (function (BABYLON) {
  46081. /**
  46082. * A directional light is defined by a direction (what a surprise!).
  46083. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  46084. * 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.
  46085. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46086. */
  46087. var DirectionalLight = /** @class */ (function (_super) {
  46088. __extends(DirectionalLight, _super);
  46089. /**
  46090. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  46091. * The directional light is emitted from everywhere in the given direction.
  46092. * It can cast shawdows.
  46093. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46094. * @param name The friendly name of the light
  46095. * @param direction The direction of the light
  46096. * @param scene The scene the light belongs to
  46097. */
  46098. function DirectionalLight(name, direction, scene) {
  46099. var _this = _super.call(this, name, scene) || this;
  46100. _this._shadowFrustumSize = 0;
  46101. _this._shadowOrthoScale = 0.1;
  46102. /**
  46103. * Automatically compute the projection matrix to best fit (including all the casters)
  46104. * on each frame.
  46105. */
  46106. _this.autoUpdateExtends = true;
  46107. // Cache
  46108. _this._orthoLeft = Number.MAX_VALUE;
  46109. _this._orthoRight = Number.MIN_VALUE;
  46110. _this._orthoTop = Number.MIN_VALUE;
  46111. _this._orthoBottom = Number.MAX_VALUE;
  46112. _this.position = direction.scale(-1.0);
  46113. _this.direction = direction;
  46114. return _this;
  46115. }
  46116. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  46117. /**
  46118. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  46119. */
  46120. get: function () {
  46121. return this._shadowFrustumSize;
  46122. },
  46123. /**
  46124. * Specifies a fix frustum size for the shadow generation.
  46125. */
  46126. set: function (value) {
  46127. this._shadowFrustumSize = value;
  46128. this.forceProjectionMatrixCompute();
  46129. },
  46130. enumerable: true,
  46131. configurable: true
  46132. });
  46133. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  46134. /**
  46135. * Gets the shadow projection scale against the optimal computed one.
  46136. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  46137. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  46138. */
  46139. get: function () {
  46140. return this._shadowOrthoScale;
  46141. },
  46142. /**
  46143. * Sets the shadow projection scale against the optimal computed one.
  46144. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  46145. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  46146. */
  46147. set: function (value) {
  46148. this._shadowOrthoScale = value;
  46149. this.forceProjectionMatrixCompute();
  46150. },
  46151. enumerable: true,
  46152. configurable: true
  46153. });
  46154. /**
  46155. * Returns the string "DirectionalLight".
  46156. * @return The class name
  46157. */
  46158. DirectionalLight.prototype.getClassName = function () {
  46159. return "DirectionalLight";
  46160. };
  46161. /**
  46162. * Returns the integer 1.
  46163. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46164. */
  46165. DirectionalLight.prototype.getTypeID = function () {
  46166. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  46167. };
  46168. /**
  46169. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  46170. * Returns the DirectionalLight Shadow projection matrix.
  46171. */
  46172. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46173. if (this.shadowFrustumSize > 0) {
  46174. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  46175. }
  46176. else {
  46177. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  46178. }
  46179. };
  46180. /**
  46181. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  46182. * Returns the DirectionalLight Shadow projection matrix.
  46183. */
  46184. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  46185. var activeCamera = this.getScene().activeCamera;
  46186. if (!activeCamera) {
  46187. return;
  46188. }
  46189. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  46190. };
  46191. /**
  46192. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  46193. * Returns the DirectionalLight Shadow projection matrix.
  46194. */
  46195. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46196. var activeCamera = this.getScene().activeCamera;
  46197. if (!activeCamera) {
  46198. return;
  46199. }
  46200. // Check extends
  46201. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  46202. var tempVector3 = BABYLON.Vector3.Zero();
  46203. this._orthoLeft = Number.MAX_VALUE;
  46204. this._orthoRight = Number.MIN_VALUE;
  46205. this._orthoTop = Number.MIN_VALUE;
  46206. this._orthoBottom = Number.MAX_VALUE;
  46207. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  46208. var mesh = renderList[meshIndex];
  46209. if (!mesh) {
  46210. continue;
  46211. }
  46212. var boundingInfo = mesh.getBoundingInfo();
  46213. var boundingBox = boundingInfo.boundingBox;
  46214. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  46215. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  46216. if (tempVector3.x < this._orthoLeft)
  46217. this._orthoLeft = tempVector3.x;
  46218. if (tempVector3.y < this._orthoBottom)
  46219. this._orthoBottom = tempVector3.y;
  46220. if (tempVector3.x > this._orthoRight)
  46221. this._orthoRight = tempVector3.x;
  46222. if (tempVector3.y > this._orthoTop)
  46223. this._orthoTop = tempVector3.y;
  46224. }
  46225. }
  46226. }
  46227. var xOffset = this._orthoRight - this._orthoLeft;
  46228. var yOffset = this._orthoTop - this._orthoBottom;
  46229. 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);
  46230. };
  46231. DirectionalLight.prototype._buildUniformLayout = function () {
  46232. this._uniformBuffer.addUniform("vLightData", 4);
  46233. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46234. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46235. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46236. this._uniformBuffer.addUniform("depthValues", 2);
  46237. this._uniformBuffer.create();
  46238. };
  46239. /**
  46240. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  46241. * @param effect The effect to update
  46242. * @param lightIndex The index of the light in the effect to update
  46243. * @returns The directional light
  46244. */
  46245. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  46246. if (this.computeTransformedInformation()) {
  46247. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  46248. return this;
  46249. }
  46250. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  46251. return this;
  46252. };
  46253. /**
  46254. * Gets the minZ used for shadow according to both the scene and the light.
  46255. *
  46256. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46257. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46258. * @param activeCamera The camera we are returning the min for
  46259. * @returns the depth min z
  46260. */
  46261. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  46262. return 1;
  46263. };
  46264. /**
  46265. * Gets the maxZ used for shadow according to both the scene and the light.
  46266. *
  46267. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46268. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46269. * @param activeCamera The camera we are returning the max for
  46270. * @returns the depth max z
  46271. */
  46272. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  46273. return 1;
  46274. };
  46275. __decorate([
  46276. BABYLON.serialize()
  46277. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  46278. __decorate([
  46279. BABYLON.serialize()
  46280. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  46281. __decorate([
  46282. BABYLON.serialize()
  46283. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  46284. return DirectionalLight;
  46285. }(BABYLON.ShadowLight));
  46286. BABYLON.DirectionalLight = DirectionalLight;
  46287. })(BABYLON || (BABYLON = {}));
  46288. //# sourceMappingURL=babylon.directionalLight.js.map
  46289. var BABYLON;
  46290. (function (BABYLON) {
  46291. /**
  46292. * A spot light is defined by a position, a direction, an angle, and an exponent.
  46293. * These values define a cone of light starting from the position, emitting toward the direction.
  46294. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  46295. * and the exponent defines the speed of the decay of the light with distance (reach).
  46296. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46297. */
  46298. var SpotLight = /** @class */ (function (_super) {
  46299. __extends(SpotLight, _super);
  46300. /**
  46301. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  46302. * It can cast shadows.
  46303. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46304. * @param name The light friendly name
  46305. * @param position The position of the spot light in the scene
  46306. * @param direction The direction of the light in the scene
  46307. * @param angle The cone angle of the light in Radians
  46308. * @param exponent The light decay speed with the distance from the emission spot
  46309. * @param scene The scene the lights belongs to
  46310. */
  46311. function SpotLight(name, position, direction, angle, exponent, scene) {
  46312. var _this = _super.call(this, name, scene) || this;
  46313. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  46314. _this._projectionTextureLightNear = 1e-6;
  46315. _this._projectionTextureLightFar = 1000.0;
  46316. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  46317. _this._projectionTextureViewLightDirty = true;
  46318. _this._projectionTextureProjectionLightDirty = true;
  46319. _this._projectionTextureDirty = true;
  46320. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  46321. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  46322. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  46323. _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);
  46324. _this.position = position;
  46325. _this.direction = direction;
  46326. _this.angle = angle;
  46327. _this.exponent = exponent;
  46328. return _this;
  46329. }
  46330. Object.defineProperty(SpotLight.prototype, "angle", {
  46331. /**
  46332. * Gets the cone angle of the spot light in Radians.
  46333. */
  46334. get: function () {
  46335. return this._angle;
  46336. },
  46337. /**
  46338. * Sets the cone angle of the spot light in Radians.
  46339. */
  46340. set: function (value) {
  46341. this._angle = value;
  46342. this._projectionTextureProjectionLightDirty = true;
  46343. this.forceProjectionMatrixCompute();
  46344. },
  46345. enumerable: true,
  46346. configurable: true
  46347. });
  46348. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  46349. /**
  46350. * Allows scaling the angle of the light for shadow generation only.
  46351. */
  46352. get: function () {
  46353. return this._shadowAngleScale;
  46354. },
  46355. /**
  46356. * Allows scaling the angle of the light for shadow generation only.
  46357. */
  46358. set: function (value) {
  46359. this._shadowAngleScale = value;
  46360. this.forceProjectionMatrixCompute();
  46361. },
  46362. enumerable: true,
  46363. configurable: true
  46364. });
  46365. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  46366. /**
  46367. * Allows reading the projecton texture
  46368. */
  46369. get: function () {
  46370. return this._projectionTextureMatrix;
  46371. },
  46372. enumerable: true,
  46373. configurable: true
  46374. });
  46375. ;
  46376. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  46377. /**
  46378. * Gets the near clip of the Spotlight for texture projection.
  46379. */
  46380. get: function () {
  46381. return this._projectionTextureLightNear;
  46382. },
  46383. /**
  46384. * Sets the near clip of the Spotlight for texture projection.
  46385. */
  46386. set: function (value) {
  46387. this._projectionTextureLightNear = value;
  46388. this._projectionTextureProjectionLightDirty = true;
  46389. },
  46390. enumerable: true,
  46391. configurable: true
  46392. });
  46393. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  46394. /**
  46395. * Gets the far clip of the Spotlight for texture projection.
  46396. */
  46397. get: function () {
  46398. return this._projectionTextureLightFar;
  46399. },
  46400. /**
  46401. * Sets the far clip of the Spotlight for texture projection.
  46402. */
  46403. set: function (value) {
  46404. this._projectionTextureLightFar = value;
  46405. this._projectionTextureProjectionLightDirty = true;
  46406. },
  46407. enumerable: true,
  46408. configurable: true
  46409. });
  46410. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  46411. /**
  46412. * Gets the Up vector of the Spotlight for texture projection.
  46413. */
  46414. get: function () {
  46415. return this._projectionTextureUpDirection;
  46416. },
  46417. /**
  46418. * Sets the Up vector of the Spotlight for texture projection.
  46419. */
  46420. set: function (value) {
  46421. this._projectionTextureUpDirection = value;
  46422. this._projectionTextureProjectionLightDirty = true;
  46423. },
  46424. enumerable: true,
  46425. configurable: true
  46426. });
  46427. ;
  46428. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  46429. /**
  46430. * Gets the projection texture of the light.
  46431. */
  46432. get: function () {
  46433. return this._projectionTexture;
  46434. },
  46435. /**
  46436. * Sets the projection texture of the light.
  46437. */
  46438. set: function (value) {
  46439. this._projectionTexture = value;
  46440. this._projectionTextureDirty = true;
  46441. },
  46442. enumerable: true,
  46443. configurable: true
  46444. });
  46445. /**
  46446. * Returns the string "SpotLight".
  46447. * @returns the class name
  46448. */
  46449. SpotLight.prototype.getClassName = function () {
  46450. return "SpotLight";
  46451. };
  46452. /**
  46453. * Returns the integer 2.
  46454. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46455. */
  46456. SpotLight.prototype.getTypeID = function () {
  46457. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  46458. };
  46459. /**
  46460. * Overrides the direction setter to recompute the projection texture view light Matrix.
  46461. */
  46462. SpotLight.prototype._setDirection = function (value) {
  46463. _super.prototype._setDirection.call(this, value);
  46464. this._projectionTextureViewLightDirty = true;
  46465. };
  46466. /**
  46467. * Overrides the position setter to recompute the projection texture view light Matrix.
  46468. */
  46469. SpotLight.prototype._setPosition = function (value) {
  46470. _super.prototype._setPosition.call(this, value);
  46471. this._projectionTextureViewLightDirty = true;
  46472. };
  46473. /**
  46474. * 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.
  46475. * Returns the SpotLight.
  46476. */
  46477. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46478. var activeCamera = this.getScene().activeCamera;
  46479. if (!activeCamera) {
  46480. return;
  46481. }
  46482. this._shadowAngleScale = this._shadowAngleScale || 1;
  46483. var angle = this._shadowAngleScale * this._angle;
  46484. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46485. };
  46486. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  46487. this._projectionTextureViewLightDirty = false;
  46488. this._projectionTextureDirty = true;
  46489. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  46490. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  46491. };
  46492. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  46493. this._projectionTextureProjectionLightDirty = false;
  46494. this._projectionTextureDirty = true;
  46495. var light_far = this.projectionTextureLightFar;
  46496. var light_near = this.projectionTextureLightNear;
  46497. var P = light_far / (light_far - light_near);
  46498. var Q = -P * light_near;
  46499. var S = 1.0 / Math.tan(this._angle / 2.0);
  46500. var A = 1.0;
  46501. 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);
  46502. };
  46503. /**
  46504. * Main function for light texture projection matrix computing.
  46505. */
  46506. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  46507. this._projectionTextureDirty = false;
  46508. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  46509. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  46510. };
  46511. SpotLight.prototype._buildUniformLayout = function () {
  46512. this._uniformBuffer.addUniform("vLightData", 4);
  46513. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46514. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46515. this._uniformBuffer.addUniform("vLightDirection", 3);
  46516. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46517. this._uniformBuffer.addUniform("depthValues", 2);
  46518. this._uniformBuffer.create();
  46519. };
  46520. /**
  46521. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  46522. * @param effect The effect to update
  46523. * @param lightIndex The index of the light in the effect to update
  46524. * @returns The spot light
  46525. */
  46526. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  46527. var normalizeDirection;
  46528. if (this.computeTransformedInformation()) {
  46529. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  46530. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  46531. }
  46532. else {
  46533. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  46534. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  46535. }
  46536. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  46537. if (this.projectionTexture && this.projectionTexture.isReady()) {
  46538. if (this._projectionTextureViewLightDirty) {
  46539. this._computeProjectionTextureViewLightMatrix();
  46540. }
  46541. if (this._projectionTextureProjectionLightDirty) {
  46542. this._computeProjectionTextureProjectionLightMatrix();
  46543. }
  46544. if (this._projectionTextureDirty) {
  46545. this._computeProjectionTextureMatrix();
  46546. }
  46547. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  46548. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  46549. }
  46550. return this;
  46551. };
  46552. /**
  46553. * Disposes the light and the associated resources.
  46554. */
  46555. SpotLight.prototype.dispose = function () {
  46556. _super.prototype.dispose.call(this);
  46557. if (this._projectionTexture) {
  46558. this._projectionTexture.dispose();
  46559. }
  46560. };
  46561. __decorate([
  46562. BABYLON.serialize()
  46563. ], SpotLight.prototype, "angle", null);
  46564. __decorate([
  46565. BABYLON.serialize()
  46566. ], SpotLight.prototype, "shadowAngleScale", null);
  46567. __decorate([
  46568. BABYLON.serialize()
  46569. ], SpotLight.prototype, "exponent", void 0);
  46570. __decorate([
  46571. BABYLON.serialize()
  46572. ], SpotLight.prototype, "projectionTextureLightNear", null);
  46573. __decorate([
  46574. BABYLON.serialize()
  46575. ], SpotLight.prototype, "projectionTextureLightFar", null);
  46576. __decorate([
  46577. BABYLON.serialize()
  46578. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46579. __decorate([
  46580. BABYLON.serializeAsTexture("projectedLightTexture")
  46581. ], SpotLight.prototype, "_projectionTexture", void 0);
  46582. return SpotLight;
  46583. }(BABYLON.ShadowLight));
  46584. BABYLON.SpotLight = SpotLight;
  46585. })(BABYLON || (BABYLON = {}));
  46586. //# sourceMappingURL=babylon.spotLight.js.map
  46587. var BABYLON;
  46588. (function (BABYLON) {
  46589. /**
  46590. * Class used to override all child animations of a given target
  46591. */
  46592. var AnimationPropertiesOverride = /** @class */ (function () {
  46593. function AnimationPropertiesOverride() {
  46594. /**
  46595. * Gets or sets a value indicating if animation blending must be used
  46596. */
  46597. this.enableBlending = false;
  46598. /**
  46599. * Gets or sets the blending speed to use when enableBlending is true
  46600. */
  46601. this.blendingSpeed = 0.01;
  46602. /**
  46603. * Gets or sets the default loop mode to use
  46604. */
  46605. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  46606. }
  46607. return AnimationPropertiesOverride;
  46608. }());
  46609. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  46610. })(BABYLON || (BABYLON = {}));
  46611. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  46612. var BABYLON;
  46613. (function (BABYLON) {
  46614. var AnimationRange = /** @class */ (function () {
  46615. function AnimationRange(name, from, to) {
  46616. this.name = name;
  46617. this.from = from;
  46618. this.to = to;
  46619. }
  46620. AnimationRange.prototype.clone = function () {
  46621. return new AnimationRange(this.name, this.from, this.to);
  46622. };
  46623. return AnimationRange;
  46624. }());
  46625. BABYLON.AnimationRange = AnimationRange;
  46626. /**
  46627. * Composed of a frame, and an action function
  46628. */
  46629. var AnimationEvent = /** @class */ (function () {
  46630. function AnimationEvent(frame, action, onlyOnce) {
  46631. this.frame = frame;
  46632. this.action = action;
  46633. this.onlyOnce = onlyOnce;
  46634. this.isDone = false;
  46635. }
  46636. return AnimationEvent;
  46637. }());
  46638. BABYLON.AnimationEvent = AnimationEvent;
  46639. var PathCursor = /** @class */ (function () {
  46640. function PathCursor(path) {
  46641. this.path = path;
  46642. this._onchange = new Array();
  46643. this.value = 0;
  46644. this.animations = new Array();
  46645. }
  46646. PathCursor.prototype.getPoint = function () {
  46647. var point = this.path.getPointAtLengthPosition(this.value);
  46648. return new BABYLON.Vector3(point.x, 0, point.y);
  46649. };
  46650. PathCursor.prototype.moveAhead = function (step) {
  46651. if (step === void 0) { step = 0.002; }
  46652. this.move(step);
  46653. return this;
  46654. };
  46655. PathCursor.prototype.moveBack = function (step) {
  46656. if (step === void 0) { step = 0.002; }
  46657. this.move(-step);
  46658. return this;
  46659. };
  46660. PathCursor.prototype.move = function (step) {
  46661. if (Math.abs(step) > 1) {
  46662. throw "step size should be less than 1.";
  46663. }
  46664. this.value += step;
  46665. this.ensureLimits();
  46666. this.raiseOnChange();
  46667. return this;
  46668. };
  46669. PathCursor.prototype.ensureLimits = function () {
  46670. while (this.value > 1) {
  46671. this.value -= 1;
  46672. }
  46673. while (this.value < 0) {
  46674. this.value += 1;
  46675. }
  46676. return this;
  46677. };
  46678. // used by animation engine
  46679. PathCursor.prototype.raiseOnChange = function () {
  46680. var _this = this;
  46681. this._onchange.forEach(function (f) { return f(_this); });
  46682. return this;
  46683. };
  46684. PathCursor.prototype.onchange = function (f) {
  46685. this._onchange.push(f);
  46686. return this;
  46687. };
  46688. return PathCursor;
  46689. }());
  46690. BABYLON.PathCursor = PathCursor;
  46691. var AnimationKeyInterpolation;
  46692. (function (AnimationKeyInterpolation) {
  46693. /**
  46694. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46695. */
  46696. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46697. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46698. var Animation = /** @class */ (function () {
  46699. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46700. this.name = name;
  46701. this.targetProperty = targetProperty;
  46702. this.framePerSecond = framePerSecond;
  46703. this.dataType = dataType;
  46704. this.loopMode = loopMode;
  46705. this.enableBlending = enableBlending;
  46706. this._runtimeAnimations = new Array();
  46707. // The set of event that will be linked to this animation
  46708. this._events = new Array();
  46709. this.blendingSpeed = 0.01;
  46710. this._ranges = {};
  46711. this.targetPropertyPath = targetProperty.split(".");
  46712. this.dataType = dataType;
  46713. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46714. }
  46715. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46716. var dataType = undefined;
  46717. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46718. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46719. }
  46720. else if (from instanceof BABYLON.Quaternion) {
  46721. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46722. }
  46723. else if (from instanceof BABYLON.Vector3) {
  46724. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46725. }
  46726. else if (from instanceof BABYLON.Vector2) {
  46727. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46728. }
  46729. else if (from instanceof BABYLON.Color3) {
  46730. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46731. }
  46732. else if (from instanceof BABYLON.Size) {
  46733. dataType = Animation.ANIMATIONTYPE_SIZE;
  46734. }
  46735. if (dataType == undefined) {
  46736. return null;
  46737. }
  46738. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46739. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46740. animation.setKeys(keys);
  46741. if (easingFunction !== undefined) {
  46742. animation.setEasingFunction(easingFunction);
  46743. }
  46744. return animation;
  46745. };
  46746. /**
  46747. * Sets up an animation.
  46748. * @param property the property to animate
  46749. * @param animationType the animation type to apply
  46750. * @param easingFunction the easing function used in the animation
  46751. * @returns The created animation
  46752. */
  46753. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  46754. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  46755. animation.setEasingFunction(easingFunction);
  46756. return animation;
  46757. };
  46758. /**
  46759. * Create and start an animation on a node
  46760. * @param {string} name defines the name of the global animation that will be run on all nodes
  46761. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46762. * @param {string} targetProperty defines property to animate
  46763. * @param {number} framePerSecond defines the number of frame per second yo use
  46764. * @param {number} totalFrame defines the number of frames in total
  46765. * @param {any} from defines the initial value
  46766. * @param {any} to defines the final value
  46767. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46768. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46769. * @param onAnimationEnd defines the callback to call when animation end
  46770. * @returns the animatable created for this animation
  46771. */
  46772. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46773. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46774. if (!animation) {
  46775. return null;
  46776. }
  46777. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46778. };
  46779. /**
  46780. * Create and start an animation on a node and its descendants
  46781. * @param {string} name defines the name of the global animation that will be run on all nodes
  46782. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46783. * @param {boolean} 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.
  46784. * @param {string} targetProperty defines property to animate
  46785. * @param {number} framePerSecond defines the number of frame per second yo use
  46786. * @param {number} totalFrame defines the number of frames in total
  46787. * @param {any} from defines the initial value
  46788. * @param {any} to defines the final value
  46789. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46790. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46791. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  46792. * @returns the list of animatables created for all nodes
  46793. * @example https://www.babylonjs-playground.com/#MH0VLI
  46794. */
  46795. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46796. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46797. if (!animation) {
  46798. return null;
  46799. }
  46800. var scene = node.getScene();
  46801. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46802. };
  46803. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46804. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46805. if (!animation) {
  46806. return null;
  46807. }
  46808. node.animations.push(animation);
  46809. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46810. };
  46811. /**
  46812. * Transition property of the Camera to the target Value.
  46813. * @param property The property to transition
  46814. * @param targetValue The target Value of the property
  46815. * @param host The object where the property to animate belongs
  46816. * @param scene Scene used to run the animation
  46817. * @param frameRate Framerate (in frame/s) to use
  46818. * @param transition The transition type we want to use
  46819. * @param duration The duration of the animation, in milliseconds
  46820. * @param onAnimationEnd Call back trigger at the end of the animation.
  46821. */
  46822. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  46823. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  46824. if (duration <= 0) {
  46825. host[property] = targetValue;
  46826. if (onAnimationEnd) {
  46827. onAnimationEnd();
  46828. }
  46829. return null;
  46830. }
  46831. var endFrame = frameRate * (duration / 1000);
  46832. transition.setKeys([{
  46833. frame: 0,
  46834. value: host[property].clone ? host[property].clone() : host[property]
  46835. },
  46836. {
  46837. frame: endFrame,
  46838. value: targetValue
  46839. }]);
  46840. if (!host.animations) {
  46841. host.animations = [];
  46842. }
  46843. host.animations.push(transition);
  46844. var animation = scene.beginAnimation(host, 0, endFrame, false);
  46845. animation.onAnimationEnd = onAnimationEnd;
  46846. return animation;
  46847. };
  46848. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  46849. /**
  46850. * Return the array of runtime animations currently using this animation
  46851. */
  46852. get: function () {
  46853. return this._runtimeAnimations;
  46854. },
  46855. enumerable: true,
  46856. configurable: true
  46857. });
  46858. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  46859. get: function () {
  46860. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  46861. var runtimeAnimation = _a[_i];
  46862. if (!runtimeAnimation.isStopped) {
  46863. return true;
  46864. }
  46865. }
  46866. return false;
  46867. },
  46868. enumerable: true,
  46869. configurable: true
  46870. });
  46871. // Methods
  46872. /**
  46873. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  46874. */
  46875. Animation.prototype.toString = function (fullDetails) {
  46876. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  46877. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  46878. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  46879. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  46880. if (fullDetails) {
  46881. ret += ", Ranges: {";
  46882. var first = true;
  46883. for (var name in this._ranges) {
  46884. if (first) {
  46885. ret += ", ";
  46886. first = false;
  46887. }
  46888. ret += name;
  46889. }
  46890. ret += "}";
  46891. }
  46892. return ret;
  46893. };
  46894. /**
  46895. * Add an event to this animation.
  46896. */
  46897. Animation.prototype.addEvent = function (event) {
  46898. this._events.push(event);
  46899. };
  46900. /**
  46901. * Remove all events found at the given frame
  46902. * @param frame
  46903. */
  46904. Animation.prototype.removeEvents = function (frame) {
  46905. for (var index = 0; index < this._events.length; index++) {
  46906. if (this._events[index].frame === frame) {
  46907. this._events.splice(index, 1);
  46908. index--;
  46909. }
  46910. }
  46911. };
  46912. Animation.prototype.getEvents = function () {
  46913. return this._events;
  46914. };
  46915. Animation.prototype.createRange = function (name, from, to) {
  46916. // check name not already in use; could happen for bones after serialized
  46917. if (!this._ranges[name]) {
  46918. this._ranges[name] = new AnimationRange(name, from, to);
  46919. }
  46920. };
  46921. Animation.prototype.deleteRange = function (name, deleteFrames) {
  46922. if (deleteFrames === void 0) { deleteFrames = true; }
  46923. var range = this._ranges[name];
  46924. if (!range) {
  46925. return;
  46926. }
  46927. if (deleteFrames) {
  46928. var from = range.from;
  46929. var to = range.to;
  46930. // this loop MUST go high to low for multiple splices to work
  46931. for (var key = this._keys.length - 1; key >= 0; key--) {
  46932. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  46933. this._keys.splice(key, 1);
  46934. }
  46935. }
  46936. }
  46937. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  46938. };
  46939. Animation.prototype.getRange = function (name) {
  46940. return this._ranges[name];
  46941. };
  46942. Animation.prototype.getKeys = function () {
  46943. return this._keys;
  46944. };
  46945. Animation.prototype.getHighestFrame = function () {
  46946. var ret = 0;
  46947. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  46948. if (ret < this._keys[key].frame) {
  46949. ret = this._keys[key].frame;
  46950. }
  46951. }
  46952. return ret;
  46953. };
  46954. Animation.prototype.getEasingFunction = function () {
  46955. return this._easingFunction;
  46956. };
  46957. Animation.prototype.setEasingFunction = function (easingFunction) {
  46958. this._easingFunction = easingFunction;
  46959. };
  46960. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  46961. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  46962. };
  46963. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46964. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46965. };
  46966. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  46967. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  46968. };
  46969. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46970. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  46971. };
  46972. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  46973. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  46974. };
  46975. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46976. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46977. };
  46978. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  46979. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  46980. };
  46981. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46982. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46983. };
  46984. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  46985. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  46986. };
  46987. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  46988. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  46989. };
  46990. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  46991. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  46992. };
  46993. Animation.prototype.clone = function () {
  46994. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  46995. clone.enableBlending = this.enableBlending;
  46996. clone.blendingSpeed = this.blendingSpeed;
  46997. if (this._keys) {
  46998. clone.setKeys(this._keys);
  46999. }
  47000. if (this._ranges) {
  47001. clone._ranges = {};
  47002. for (var name in this._ranges) {
  47003. var range = this._ranges[name];
  47004. if (!range) {
  47005. continue;
  47006. }
  47007. clone._ranges[name] = range.clone();
  47008. }
  47009. }
  47010. return clone;
  47011. };
  47012. Animation.prototype.setKeys = function (values) {
  47013. this._keys = values.slice(0);
  47014. };
  47015. Animation.prototype.serialize = function () {
  47016. var serializationObject = {};
  47017. serializationObject.name = this.name;
  47018. serializationObject.property = this.targetProperty;
  47019. serializationObject.framePerSecond = this.framePerSecond;
  47020. serializationObject.dataType = this.dataType;
  47021. serializationObject.loopBehavior = this.loopMode;
  47022. serializationObject.enableBlending = this.enableBlending;
  47023. serializationObject.blendingSpeed = this.blendingSpeed;
  47024. var dataType = this.dataType;
  47025. serializationObject.keys = [];
  47026. var keys = this.getKeys();
  47027. for (var index = 0; index < keys.length; index++) {
  47028. var animationKey = keys[index];
  47029. var key = {};
  47030. key.frame = animationKey.frame;
  47031. switch (dataType) {
  47032. case Animation.ANIMATIONTYPE_FLOAT:
  47033. key.values = [animationKey.value];
  47034. break;
  47035. case Animation.ANIMATIONTYPE_QUATERNION:
  47036. case Animation.ANIMATIONTYPE_MATRIX:
  47037. case Animation.ANIMATIONTYPE_VECTOR3:
  47038. case Animation.ANIMATIONTYPE_COLOR3:
  47039. key.values = animationKey.value.asArray();
  47040. break;
  47041. }
  47042. serializationObject.keys.push(key);
  47043. }
  47044. serializationObject.ranges = [];
  47045. for (var name in this._ranges) {
  47046. var source = this._ranges[name];
  47047. if (!source) {
  47048. continue;
  47049. }
  47050. var range = {};
  47051. range.name = name;
  47052. range.from = source.from;
  47053. range.to = source.to;
  47054. serializationObject.ranges.push(range);
  47055. }
  47056. return serializationObject;
  47057. };
  47058. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  47059. get: function () {
  47060. return Animation._ANIMATIONTYPE_FLOAT;
  47061. },
  47062. enumerable: true,
  47063. configurable: true
  47064. });
  47065. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  47066. get: function () {
  47067. return Animation._ANIMATIONTYPE_VECTOR3;
  47068. },
  47069. enumerable: true,
  47070. configurable: true
  47071. });
  47072. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  47073. get: function () {
  47074. return Animation._ANIMATIONTYPE_VECTOR2;
  47075. },
  47076. enumerable: true,
  47077. configurable: true
  47078. });
  47079. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  47080. get: function () {
  47081. return Animation._ANIMATIONTYPE_SIZE;
  47082. },
  47083. enumerable: true,
  47084. configurable: true
  47085. });
  47086. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  47087. get: function () {
  47088. return Animation._ANIMATIONTYPE_QUATERNION;
  47089. },
  47090. enumerable: true,
  47091. configurable: true
  47092. });
  47093. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  47094. get: function () {
  47095. return Animation._ANIMATIONTYPE_MATRIX;
  47096. },
  47097. enumerable: true,
  47098. configurable: true
  47099. });
  47100. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  47101. get: function () {
  47102. return Animation._ANIMATIONTYPE_COLOR3;
  47103. },
  47104. enumerable: true,
  47105. configurable: true
  47106. });
  47107. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  47108. get: function () {
  47109. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  47110. },
  47111. enumerable: true,
  47112. configurable: true
  47113. });
  47114. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  47115. get: function () {
  47116. return Animation._ANIMATIONLOOPMODE_CYCLE;
  47117. },
  47118. enumerable: true,
  47119. configurable: true
  47120. });
  47121. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  47122. get: function () {
  47123. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  47124. },
  47125. enumerable: true,
  47126. configurable: true
  47127. });
  47128. Animation.Parse = function (parsedAnimation) {
  47129. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  47130. var dataType = parsedAnimation.dataType;
  47131. var keys = [];
  47132. var data;
  47133. var index;
  47134. if (parsedAnimation.enableBlending) {
  47135. animation.enableBlending = parsedAnimation.enableBlending;
  47136. }
  47137. if (parsedAnimation.blendingSpeed) {
  47138. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  47139. }
  47140. for (index = 0; index < parsedAnimation.keys.length; index++) {
  47141. var key = parsedAnimation.keys[index];
  47142. var inTangent;
  47143. var outTangent;
  47144. switch (dataType) {
  47145. case Animation.ANIMATIONTYPE_FLOAT:
  47146. data = key.values[0];
  47147. if (key.values.length >= 1) {
  47148. inTangent = key.values[1];
  47149. }
  47150. if (key.values.length >= 2) {
  47151. outTangent = key.values[2];
  47152. }
  47153. break;
  47154. case Animation.ANIMATIONTYPE_QUATERNION:
  47155. data = BABYLON.Quaternion.FromArray(key.values);
  47156. if (key.values.length >= 8) {
  47157. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  47158. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  47159. inTangent = _inTangent;
  47160. }
  47161. }
  47162. if (key.values.length >= 12) {
  47163. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  47164. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  47165. outTangent = _outTangent;
  47166. }
  47167. }
  47168. break;
  47169. case Animation.ANIMATIONTYPE_MATRIX:
  47170. data = BABYLON.Matrix.FromArray(key.values);
  47171. break;
  47172. case Animation.ANIMATIONTYPE_COLOR3:
  47173. data = BABYLON.Color3.FromArray(key.values);
  47174. break;
  47175. case Animation.ANIMATIONTYPE_VECTOR3:
  47176. default:
  47177. data = BABYLON.Vector3.FromArray(key.values);
  47178. break;
  47179. }
  47180. var keyData = {};
  47181. keyData.frame = key.frame;
  47182. keyData.value = data;
  47183. if (inTangent != undefined) {
  47184. keyData.inTangent = inTangent;
  47185. }
  47186. if (outTangent != undefined) {
  47187. keyData.outTangent = outTangent;
  47188. }
  47189. keys.push(keyData);
  47190. }
  47191. animation.setKeys(keys);
  47192. if (parsedAnimation.ranges) {
  47193. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  47194. data = parsedAnimation.ranges[index];
  47195. animation.createRange(data.name, data.from, data.to);
  47196. }
  47197. }
  47198. return animation;
  47199. };
  47200. Animation.AppendSerializedAnimations = function (source, destination) {
  47201. if (source.animations) {
  47202. destination.animations = [];
  47203. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  47204. var animation = source.animations[animationIndex];
  47205. destination.animations.push(animation.serialize());
  47206. }
  47207. }
  47208. };
  47209. Animation.AllowMatricesInterpolation = false;
  47210. // Statics
  47211. Animation._ANIMATIONTYPE_FLOAT = 0;
  47212. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  47213. Animation._ANIMATIONTYPE_QUATERNION = 2;
  47214. Animation._ANIMATIONTYPE_MATRIX = 3;
  47215. Animation._ANIMATIONTYPE_COLOR3 = 4;
  47216. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  47217. Animation._ANIMATIONTYPE_SIZE = 6;
  47218. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  47219. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  47220. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  47221. return Animation;
  47222. }());
  47223. BABYLON.Animation = Animation;
  47224. })(BABYLON || (BABYLON = {}));
  47225. //# sourceMappingURL=babylon.animation.js.map
  47226. var BABYLON;
  47227. (function (BABYLON) {
  47228. /**
  47229. * This class defines the direct association between an animation and a target
  47230. */
  47231. var TargetedAnimation = /** @class */ (function () {
  47232. function TargetedAnimation() {
  47233. }
  47234. return TargetedAnimation;
  47235. }());
  47236. BABYLON.TargetedAnimation = TargetedAnimation;
  47237. /**
  47238. * Use this class to create coordinated animations on multiple targets
  47239. */
  47240. var AnimationGroup = /** @class */ (function () {
  47241. function AnimationGroup(name, scene) {
  47242. if (scene === void 0) { scene = null; }
  47243. this.name = name;
  47244. this._targetedAnimations = new Array();
  47245. this._animatables = new Array();
  47246. this._from = Number.MAX_VALUE;
  47247. this._to = -Number.MAX_VALUE;
  47248. this._speedRatio = 1;
  47249. this.onAnimationEndObservable = new BABYLON.Observable();
  47250. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47251. this._scene.animationGroups.push(this);
  47252. }
  47253. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  47254. /**
  47255. * Define if the animations are started
  47256. */
  47257. get: function () {
  47258. return this._isStarted;
  47259. },
  47260. enumerable: true,
  47261. configurable: true
  47262. });
  47263. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  47264. /**
  47265. * Gets or sets the speed ratio to use for all animations
  47266. */
  47267. get: function () {
  47268. return this._speedRatio;
  47269. },
  47270. /**
  47271. * Gets or sets the speed ratio to use for all animations
  47272. */
  47273. set: function (value) {
  47274. if (this._speedRatio === value) {
  47275. return;
  47276. }
  47277. this._speedRatio = value;
  47278. for (var index = 0; index < this._animatables.length; index++) {
  47279. var animatable = this._animatables[index];
  47280. animatable.speedRatio = this._speedRatio;
  47281. }
  47282. },
  47283. enumerable: true,
  47284. configurable: true
  47285. });
  47286. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  47287. /**
  47288. * Gets the targeted animations for this animation group
  47289. */
  47290. get: function () {
  47291. return this._targetedAnimations;
  47292. },
  47293. enumerable: true,
  47294. configurable: true
  47295. });
  47296. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  47297. /**
  47298. * returning the list of animatables controlled by this animation group.
  47299. */
  47300. get: function () {
  47301. return this._animatables;
  47302. },
  47303. enumerable: true,
  47304. configurable: true
  47305. });
  47306. /**
  47307. * Add an animation (with its target) in the group
  47308. * @param animation defines the animation we want to add
  47309. * @param target defines the target of the animation
  47310. * @returns the {BABYLON.TargetedAnimation} object
  47311. */
  47312. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  47313. var targetedAnimation = {
  47314. animation: animation,
  47315. target: target
  47316. };
  47317. var keys = animation.getKeys();
  47318. if (this._from > keys[0].frame) {
  47319. this._from = keys[0].frame;
  47320. }
  47321. if (this._to < keys[keys.length - 1].frame) {
  47322. this._to = keys[keys.length - 1].frame;
  47323. }
  47324. this._targetedAnimations.push(targetedAnimation);
  47325. return targetedAnimation;
  47326. };
  47327. /**
  47328. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  47329. * It can add constant keys at begin or end
  47330. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  47331. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  47332. */
  47333. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  47334. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  47335. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  47336. beginFrame = Math.max(beginFrame, this._from);
  47337. endFrame = Math.min(endFrame, this._to);
  47338. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47339. var targetedAnimation = this._targetedAnimations[index];
  47340. var keys = targetedAnimation.animation.getKeys();
  47341. var startKey = keys[0];
  47342. var endKey = keys[keys.length - 1];
  47343. if (startKey.frame > beginFrame) {
  47344. var newKey = {
  47345. frame: beginFrame,
  47346. value: startKey.value,
  47347. inTangent: startKey.inTangent,
  47348. outTangent: startKey.outTangent,
  47349. interpolation: startKey.interpolation
  47350. };
  47351. keys.splice(0, 0, newKey);
  47352. }
  47353. if (endKey.frame < endFrame) {
  47354. var newKey = {
  47355. frame: endFrame,
  47356. value: endKey.value,
  47357. inTangent: endKey.outTangent,
  47358. outTangent: endKey.outTangent,
  47359. interpolation: endKey.interpolation
  47360. };
  47361. keys.push(newKey);
  47362. }
  47363. }
  47364. return this;
  47365. };
  47366. /**
  47367. * Start all animations on given targets
  47368. * @param loop defines if animations must loop
  47369. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  47370. */
  47371. AnimationGroup.prototype.start = function (loop, speedRatio) {
  47372. var _this = this;
  47373. if (loop === void 0) { loop = false; }
  47374. if (speedRatio === void 0) { speedRatio = 1; }
  47375. if (this._isStarted || this._targetedAnimations.length === 0) {
  47376. return this;
  47377. }
  47378. var _loop_1 = function () {
  47379. var targetedAnimation = this_1._targetedAnimations[index];
  47380. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  47381. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  47382. }));
  47383. };
  47384. var this_1 = this;
  47385. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47386. _loop_1();
  47387. }
  47388. this._speedRatio = speedRatio;
  47389. this._isStarted = true;
  47390. return this;
  47391. };
  47392. /**
  47393. * Pause all animations
  47394. */
  47395. AnimationGroup.prototype.pause = function () {
  47396. if (!this._isStarted) {
  47397. return this;
  47398. }
  47399. for (var index = 0; index < this._animatables.length; index++) {
  47400. var animatable = this._animatables[index];
  47401. animatable.pause();
  47402. }
  47403. return this;
  47404. };
  47405. /**
  47406. * Play all animations to initial state
  47407. * This function will start() the animations if they were not started or will restart() them if they were paused
  47408. * @param loop defines if animations must loop
  47409. */
  47410. AnimationGroup.prototype.play = function (loop) {
  47411. if (this.isStarted) {
  47412. if (loop !== undefined) {
  47413. for (var index = 0; index < this._animatables.length; index++) {
  47414. var animatable = this._animatables[index];
  47415. animatable.loopAnimation = loop;
  47416. }
  47417. }
  47418. this.restart();
  47419. }
  47420. else {
  47421. this.start(loop, this._speedRatio);
  47422. }
  47423. return this;
  47424. };
  47425. /**
  47426. * Reset all animations to initial state
  47427. */
  47428. AnimationGroup.prototype.reset = function () {
  47429. if (!this._isStarted) {
  47430. return this;
  47431. }
  47432. for (var index = 0; index < this._animatables.length; index++) {
  47433. var animatable = this._animatables[index];
  47434. animatable.reset();
  47435. }
  47436. return this;
  47437. };
  47438. /**
  47439. * Restart animations from key 0
  47440. */
  47441. AnimationGroup.prototype.restart = function () {
  47442. if (!this._isStarted) {
  47443. return this;
  47444. }
  47445. for (var index = 0; index < this._animatables.length; index++) {
  47446. var animatable = this._animatables[index];
  47447. animatable.restart();
  47448. }
  47449. return this;
  47450. };
  47451. /**
  47452. * Stop all animations
  47453. */
  47454. AnimationGroup.prototype.stop = function () {
  47455. if (!this._isStarted) {
  47456. return this;
  47457. }
  47458. for (var index = 0; index < this._animatables.length; index++) {
  47459. var animatable = this._animatables[index];
  47460. animatable.stop();
  47461. }
  47462. this._isStarted = false;
  47463. return this;
  47464. };
  47465. /**
  47466. * Goes to a specific frame in this animation group
  47467. *
  47468. * @param frame the frame number to go to
  47469. * @return the animationGroup
  47470. */
  47471. AnimationGroup.prototype.goToFrame = function (frame) {
  47472. if (!this._isStarted) {
  47473. return this;
  47474. }
  47475. for (var index = 0; index < this._animatables.length; index++) {
  47476. var animatable = this._animatables[index];
  47477. animatable.goToFrame(frame);
  47478. }
  47479. return this;
  47480. };
  47481. /**
  47482. * Dispose all associated resources
  47483. */
  47484. AnimationGroup.prototype.dispose = function () {
  47485. this._targetedAnimations = [];
  47486. this._animatables = [];
  47487. var index = this._scene.animationGroups.indexOf(this);
  47488. if (index > -1) {
  47489. this._scene.animationGroups.splice(index, 1);
  47490. }
  47491. };
  47492. return AnimationGroup;
  47493. }());
  47494. BABYLON.AnimationGroup = AnimationGroup;
  47495. })(BABYLON || (BABYLON = {}));
  47496. //# sourceMappingURL=babylon.animationGroup.js.map
  47497. var BABYLON;
  47498. (function (BABYLON) {
  47499. var RuntimeAnimation = /** @class */ (function () {
  47500. /**
  47501. * Create a new RuntimeAnimation object
  47502. * @param target defines the target of the animation
  47503. * @param animation defines the source {BABYLON.Animation} object
  47504. * @param scene defines the hosting scene
  47505. */
  47506. function RuntimeAnimation(target, animation, scene) {
  47507. this._offsetsCache = {};
  47508. this._highLimitsCache = {};
  47509. this._stopped = false;
  47510. this._blendingFactor = 0;
  47511. this._weight = 1.0;
  47512. this._ratioOffset = 0;
  47513. this._animation = animation;
  47514. this._target = target;
  47515. this._scene = scene;
  47516. animation._runtimeAnimations.push(this);
  47517. }
  47518. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  47519. /**
  47520. * Gets the weight of the runtime animation
  47521. */
  47522. get: function () {
  47523. return this._weight;
  47524. },
  47525. enumerable: true,
  47526. configurable: true
  47527. });
  47528. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  47529. /**
  47530. * Gets the original value of the runtime animation
  47531. */
  47532. get: function () {
  47533. return this._originalValue;
  47534. },
  47535. enumerable: true,
  47536. configurable: true
  47537. });
  47538. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  47539. /**
  47540. * Gets the current value of the runtime animation
  47541. */
  47542. get: function () {
  47543. return this._currentValue;
  47544. },
  47545. enumerable: true,
  47546. configurable: true
  47547. });
  47548. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  47549. /**
  47550. * Gets the path where to store the animated value in the target
  47551. */
  47552. get: function () {
  47553. return this._targetPath;
  47554. },
  47555. enumerable: true,
  47556. configurable: true
  47557. });
  47558. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  47559. /**
  47560. * Gets the actual target of the runtime animation
  47561. */
  47562. get: function () {
  47563. return this._activeTarget;
  47564. },
  47565. enumerable: true,
  47566. configurable: true
  47567. });
  47568. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  47569. get: function () {
  47570. return this._animation;
  47571. },
  47572. enumerable: true,
  47573. configurable: true
  47574. });
  47575. RuntimeAnimation.prototype.reset = function () {
  47576. this._offsetsCache = {};
  47577. this._highLimitsCache = {};
  47578. this.currentFrame = 0;
  47579. this._blendingFactor = 0;
  47580. this._originalValue = null;
  47581. };
  47582. RuntimeAnimation.prototype.isStopped = function () {
  47583. return this._stopped;
  47584. };
  47585. RuntimeAnimation.prototype.dispose = function () {
  47586. var index = this._animation.runtimeAnimations.indexOf(this);
  47587. if (index > -1) {
  47588. this._animation.runtimeAnimations.splice(index, 1);
  47589. }
  47590. };
  47591. RuntimeAnimation.prototype._getKeyValue = function (value) {
  47592. if (typeof value === "function") {
  47593. return value();
  47594. }
  47595. return value;
  47596. };
  47597. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  47598. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  47599. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  47600. }
  47601. this.currentFrame = currentFrame;
  47602. var keys = this._animation.getKeys();
  47603. // Try to get a hash to find the right key
  47604. 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));
  47605. if (keys[startKeyIndex].frame >= currentFrame) {
  47606. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  47607. startKeyIndex--;
  47608. }
  47609. }
  47610. for (var key = startKeyIndex; key < keys.length; key++) {
  47611. var endKey = keys[key + 1];
  47612. if (endKey.frame >= currentFrame) {
  47613. var startKey = keys[key];
  47614. var startValue = this._getKeyValue(startKey.value);
  47615. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  47616. return startValue;
  47617. }
  47618. var endValue = this._getKeyValue(endKey.value);
  47619. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  47620. var frameDelta = endKey.frame - startKey.frame;
  47621. // gradient : percent of currentFrame between the frame inf and the frame sup
  47622. var gradient = (currentFrame - startKey.frame) / frameDelta;
  47623. // check for easingFunction and correction of gradient
  47624. var easingFunction = this._animation.getEasingFunction();
  47625. if (easingFunction != null) {
  47626. gradient = easingFunction.ease(gradient);
  47627. }
  47628. switch (this._animation.dataType) {
  47629. // Float
  47630. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47631. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  47632. switch (loopMode) {
  47633. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47634. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47635. return floatValue;
  47636. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47637. return offsetValue * repeatCount + floatValue;
  47638. }
  47639. break;
  47640. // Quaternion
  47641. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47642. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  47643. switch (loopMode) {
  47644. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47645. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47646. return quatValue;
  47647. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47648. return quatValue.add(offsetValue.scale(repeatCount));
  47649. }
  47650. return quatValue;
  47651. // Vector3
  47652. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47653. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  47654. switch (loopMode) {
  47655. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47656. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47657. return vec3Value;
  47658. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47659. return vec3Value.add(offsetValue.scale(repeatCount));
  47660. }
  47661. // Vector2
  47662. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47663. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  47664. switch (loopMode) {
  47665. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47666. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47667. return vec2Value;
  47668. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47669. return vec2Value.add(offsetValue.scale(repeatCount));
  47670. }
  47671. // Size
  47672. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47673. switch (loopMode) {
  47674. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47675. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47676. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47677. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47678. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47679. }
  47680. // Color3
  47681. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47682. switch (loopMode) {
  47683. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47684. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47685. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47686. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47687. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47688. }
  47689. // Matrix
  47690. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47691. switch (loopMode) {
  47692. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47693. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47694. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47695. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47696. }
  47697. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47698. return startValue;
  47699. }
  47700. default:
  47701. break;
  47702. }
  47703. break;
  47704. }
  47705. }
  47706. return this._getKeyValue(keys[keys.length - 1].value);
  47707. };
  47708. /**
  47709. * Affect the interpolated value to the target
  47710. * @param currentValue defines the value computed by the animation
  47711. * @param weight defines the weight to apply to this value
  47712. */
  47713. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  47714. if (weight === void 0) { weight = 1.0; }
  47715. // Set value
  47716. var path;
  47717. var destination;
  47718. var targetPropertyPath = this._animation.targetPropertyPath;
  47719. if (targetPropertyPath.length > 1) {
  47720. var property = this._target[targetPropertyPath[0]];
  47721. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  47722. property = property[targetPropertyPath[index]];
  47723. }
  47724. path = [targetPropertyPath.length - 1];
  47725. destination = property;
  47726. }
  47727. else {
  47728. path = targetPropertyPath[0];
  47729. destination = this._target;
  47730. }
  47731. this._targetPath = path;
  47732. this._activeTarget = destination;
  47733. this._weight = weight;
  47734. // Blending
  47735. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  47736. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  47737. if (enableBlending && this._blendingFactor <= 1.0 || weight !== -1.0) {
  47738. if (!this._originalValue) {
  47739. var originalValue = void 0;
  47740. if (destination.getRestPose) {
  47741. originalValue = destination.getRestPose();
  47742. }
  47743. else {
  47744. originalValue = destination[path];
  47745. }
  47746. if (originalValue.clone) {
  47747. this._originalValue = originalValue.clone();
  47748. }
  47749. else {
  47750. this._originalValue = originalValue;
  47751. }
  47752. }
  47753. }
  47754. if (enableBlending && this._blendingFactor <= 1.0) {
  47755. if (this._originalValue.prototype) {
  47756. if (this._originalValue.prototype.Lerp) {
  47757. this._currentValue = this._originalValue.construtor.prototype.Lerp(currentValue, this._originalValue, this._blendingFactor);
  47758. }
  47759. else {
  47760. this._currentValue = currentValue;
  47761. }
  47762. }
  47763. else if (this._originalValue.m) {
  47764. this._currentValue = BABYLON.Matrix.Lerp(this._originalValue, currentValue, this._blendingFactor);
  47765. }
  47766. else {
  47767. this._currentValue = this._originalValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  47768. }
  47769. this._blendingFactor += blendingSpeed;
  47770. destination[path] = this._currentValue;
  47771. }
  47772. else {
  47773. this._currentValue = currentValue;
  47774. if (weight !== -1.0) {
  47775. this._scene._registerTargetForLateAnimationBinding(this);
  47776. }
  47777. else {
  47778. destination[path] = this._currentValue;
  47779. }
  47780. }
  47781. if (this._target.markAsDirty) {
  47782. this._target.markAsDirty(this._animation.targetProperty);
  47783. }
  47784. };
  47785. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  47786. if (this._target && this._target.animationPropertiesOverride) {
  47787. return this._target.animationPropertiesOverride.loopMode;
  47788. }
  47789. return this._animation.loopMode;
  47790. };
  47791. /**
  47792. * Move the current animation to a given frame
  47793. * @param frame defines the frame to move to
  47794. */
  47795. RuntimeAnimation.prototype.goToFrame = function (frame) {
  47796. var keys = this._animation.getKeys();
  47797. if (frame < keys[0].frame) {
  47798. frame = keys[0].frame;
  47799. }
  47800. else if (frame > keys[keys.length - 1].frame) {
  47801. frame = keys[keys.length - 1].frame;
  47802. }
  47803. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  47804. this.setValue(currentValue, -1);
  47805. };
  47806. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  47807. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  47808. this._ratioOffset = this._previousRatio - newRatio;
  47809. };
  47810. /**
  47811. * Execute the current animation
  47812. * @param delay defines the delay to add to the current frame
  47813. * @param from defines the lower bound of the animation range
  47814. * @param to defines the upper bound of the animation range
  47815. * @param loop defines if the current animation must loop
  47816. * @param speedRatio defines the current speed ratio
  47817. * @param weight defines the weight of the animation (default is -1 so no weight)
  47818. * @returns a boolean indicating if the animation has ended
  47819. */
  47820. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  47821. if (weight === void 0) { weight = -1.0; }
  47822. var targetPropertyPath = this._animation.targetPropertyPath;
  47823. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  47824. this._stopped = true;
  47825. return false;
  47826. }
  47827. var returnValue = true;
  47828. var keys = this._animation.getKeys();
  47829. // Adding a start key at frame 0 if missing
  47830. if (keys[0].frame !== 0) {
  47831. var newKey = { frame: 0, value: keys[0].value };
  47832. keys.splice(0, 0, newKey);
  47833. }
  47834. // Check limits
  47835. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  47836. from = keys[0].frame;
  47837. }
  47838. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  47839. to = keys[keys.length - 1].frame;
  47840. }
  47841. //to and from cannot be the same key
  47842. if (from === to) {
  47843. if (from > keys[0].frame) {
  47844. from--;
  47845. }
  47846. else if (to < keys[keys.length - 1].frame) {
  47847. to++;
  47848. }
  47849. }
  47850. // Compute ratio
  47851. var range = to - from;
  47852. var offsetValue;
  47853. // ratio represents the frame delta between from and to
  47854. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  47855. var highLimitValue = 0;
  47856. this._previousDelay = delay;
  47857. this._previousRatio = ratio;
  47858. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  47859. returnValue = false;
  47860. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  47861. }
  47862. else {
  47863. // Get max value if required
  47864. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  47865. var keyOffset = to.toString() + from.toString();
  47866. if (!this._offsetsCache[keyOffset]) {
  47867. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47868. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  47869. switch (this._animation.dataType) {
  47870. // Float
  47871. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47872. this._offsetsCache[keyOffset] = toValue - fromValue;
  47873. break;
  47874. // Quaternion
  47875. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47876. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47877. break;
  47878. // Vector3
  47879. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47880. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47881. // Vector2
  47882. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47883. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47884. // Size
  47885. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47886. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47887. // Color3
  47888. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47889. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  47890. default:
  47891. break;
  47892. }
  47893. this._highLimitsCache[keyOffset] = toValue;
  47894. }
  47895. highLimitValue = this._highLimitsCache[keyOffset];
  47896. offsetValue = this._offsetsCache[keyOffset];
  47897. }
  47898. }
  47899. if (offsetValue === undefined) {
  47900. switch (this._animation.dataType) {
  47901. // Float
  47902. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47903. offsetValue = 0;
  47904. break;
  47905. // Quaternion
  47906. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47907. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  47908. break;
  47909. // Vector3
  47910. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47911. offsetValue = BABYLON.Vector3.Zero();
  47912. break;
  47913. // Vector2
  47914. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47915. offsetValue = BABYLON.Vector2.Zero();
  47916. break;
  47917. // Size
  47918. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47919. offsetValue = BABYLON.Size.Zero();
  47920. break;
  47921. // Color3
  47922. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47923. offsetValue = BABYLON.Color3.Black();
  47924. }
  47925. }
  47926. // Compute value
  47927. var repeatCount = (ratio / range) >> 0;
  47928. var currentFrame = returnValue ? from + ratio % range : to;
  47929. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  47930. // Set value
  47931. this.setValue(currentValue, weight);
  47932. // Check events
  47933. var events = this._animation.getEvents();
  47934. for (var index = 0; index < events.length; index++) {
  47935. // Make sure current frame has passed event frame and that event frame is within the current range
  47936. // Also, handle both forward and reverse animations
  47937. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  47938. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  47939. var event = events[index];
  47940. if (!event.isDone) {
  47941. // If event should be done only once, remove it.
  47942. if (event.onlyOnce) {
  47943. events.splice(index, 1);
  47944. index--;
  47945. }
  47946. event.isDone = true;
  47947. event.action();
  47948. } // Don't do anything if the event has already be done.
  47949. }
  47950. else if (events[index].isDone && !events[index].onlyOnce) {
  47951. // reset event, the animation is looping
  47952. events[index].isDone = false;
  47953. }
  47954. }
  47955. if (!returnValue) {
  47956. this._stopped = true;
  47957. }
  47958. return returnValue;
  47959. };
  47960. return RuntimeAnimation;
  47961. }());
  47962. BABYLON.RuntimeAnimation = RuntimeAnimation;
  47963. })(BABYLON || (BABYLON = {}));
  47964. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  47965. var BABYLON;
  47966. (function (BABYLON) {
  47967. var Animatable = /** @class */ (function () {
  47968. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  47969. if (fromFrame === void 0) { fromFrame = 0; }
  47970. if (toFrame === void 0) { toFrame = 100; }
  47971. if (loopAnimation === void 0) { loopAnimation = false; }
  47972. if (speedRatio === void 0) { speedRatio = 1.0; }
  47973. this.target = target;
  47974. this.fromFrame = fromFrame;
  47975. this.toFrame = toFrame;
  47976. this.loopAnimation = loopAnimation;
  47977. this.onAnimationEnd = onAnimationEnd;
  47978. this._localDelayOffset = null;
  47979. this._pausedDelay = null;
  47980. this._runtimeAnimations = new Array();
  47981. this._paused = false;
  47982. this._speedRatio = 1;
  47983. this._weight = -1.0;
  47984. this.animationStarted = false;
  47985. if (animations) {
  47986. this.appendAnimations(target, animations);
  47987. }
  47988. this._speedRatio = speedRatio;
  47989. this._scene = scene;
  47990. scene._activeAnimatables.push(this);
  47991. }
  47992. Object.defineProperty(Animatable.prototype, "weight", {
  47993. /**
  47994. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  47995. */
  47996. get: function () {
  47997. return this._weight;
  47998. },
  47999. set: function (value) {
  48000. if (value === -1) {
  48001. this._weight = -1;
  48002. return;
  48003. }
  48004. // Else weight must be in [0, 1] range
  48005. this._weight = Math.min(Math.max(value, 0), 1.0);
  48006. },
  48007. enumerable: true,
  48008. configurable: true
  48009. });
  48010. Object.defineProperty(Animatable.prototype, "speedRatio", {
  48011. /**
  48012. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  48013. */
  48014. get: function () {
  48015. return this._speedRatio;
  48016. },
  48017. set: function (value) {
  48018. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  48019. var animation = this._runtimeAnimations[index];
  48020. animation._prepareForSpeedRatioChange(value);
  48021. }
  48022. this._speedRatio = value;
  48023. },
  48024. enumerable: true,
  48025. configurable: true
  48026. });
  48027. // Methods
  48028. Animatable.prototype.getAnimations = function () {
  48029. return this._runtimeAnimations;
  48030. };
  48031. Animatable.prototype.appendAnimations = function (target, animations) {
  48032. for (var index = 0; index < animations.length; index++) {
  48033. var animation = animations[index];
  48034. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene));
  48035. }
  48036. };
  48037. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  48038. var runtimeAnimations = this._runtimeAnimations;
  48039. for (var index = 0; index < runtimeAnimations.length; index++) {
  48040. if (runtimeAnimations[index].animation.targetProperty === property) {
  48041. return runtimeAnimations[index].animation;
  48042. }
  48043. }
  48044. return null;
  48045. };
  48046. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  48047. var runtimeAnimations = this._runtimeAnimations;
  48048. for (var index = 0; index < runtimeAnimations.length; index++) {
  48049. if (runtimeAnimations[index].animation.targetProperty === property) {
  48050. return runtimeAnimations[index];
  48051. }
  48052. }
  48053. return null;
  48054. };
  48055. Animatable.prototype.reset = function () {
  48056. var runtimeAnimations = this._runtimeAnimations;
  48057. for (var index = 0; index < runtimeAnimations.length; index++) {
  48058. runtimeAnimations[index].reset();
  48059. }
  48060. // Reset to original value
  48061. for (index = 0; index < runtimeAnimations.length; index++) {
  48062. var animation = runtimeAnimations[index];
  48063. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  48064. }
  48065. this._localDelayOffset = null;
  48066. this._pausedDelay = null;
  48067. };
  48068. Animatable.prototype.enableBlending = function (blendingSpeed) {
  48069. var runtimeAnimations = this._runtimeAnimations;
  48070. for (var index = 0; index < runtimeAnimations.length; index++) {
  48071. runtimeAnimations[index].animation.enableBlending = true;
  48072. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  48073. }
  48074. };
  48075. Animatable.prototype.disableBlending = function () {
  48076. var runtimeAnimations = this._runtimeAnimations;
  48077. for (var index = 0; index < runtimeAnimations.length; index++) {
  48078. runtimeAnimations[index].animation.enableBlending = false;
  48079. }
  48080. };
  48081. Animatable.prototype.goToFrame = function (frame) {
  48082. var runtimeAnimations = this._runtimeAnimations;
  48083. if (runtimeAnimations[0]) {
  48084. var fps = runtimeAnimations[0].animation.framePerSecond;
  48085. var currentFrame = runtimeAnimations[0].currentFrame;
  48086. var adjustTime = frame - currentFrame;
  48087. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  48088. if (this._localDelayOffset === null) {
  48089. this._localDelayOffset = 0;
  48090. }
  48091. this._localDelayOffset -= delay;
  48092. }
  48093. for (var index = 0; index < runtimeAnimations.length; index++) {
  48094. runtimeAnimations[index].goToFrame(frame);
  48095. }
  48096. };
  48097. Animatable.prototype.pause = function () {
  48098. if (this._paused) {
  48099. return;
  48100. }
  48101. this._paused = true;
  48102. };
  48103. Animatable.prototype.restart = function () {
  48104. this._paused = false;
  48105. };
  48106. Animatable.prototype.stop = function (animationName) {
  48107. if (animationName) {
  48108. var idx = this._scene._activeAnimatables.indexOf(this);
  48109. if (idx > -1) {
  48110. var runtimeAnimations = this._runtimeAnimations;
  48111. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  48112. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  48113. continue;
  48114. }
  48115. runtimeAnimations[index].dispose();
  48116. runtimeAnimations.splice(index, 1);
  48117. }
  48118. if (runtimeAnimations.length == 0) {
  48119. this._scene._activeAnimatables.splice(idx, 1);
  48120. if (this.onAnimationEnd) {
  48121. this.onAnimationEnd();
  48122. }
  48123. }
  48124. }
  48125. }
  48126. else {
  48127. var index = this._scene._activeAnimatables.indexOf(this);
  48128. if (index > -1) {
  48129. this._scene._activeAnimatables.splice(index, 1);
  48130. var runtimeAnimations = this._runtimeAnimations;
  48131. for (var index = 0; index < runtimeAnimations.length; index++) {
  48132. runtimeAnimations[index].dispose();
  48133. }
  48134. if (this.onAnimationEnd) {
  48135. this.onAnimationEnd();
  48136. }
  48137. }
  48138. }
  48139. };
  48140. Animatable.prototype._animate = function (delay) {
  48141. if (this._paused) {
  48142. this.animationStarted = false;
  48143. if (this._pausedDelay === null) {
  48144. this._pausedDelay = delay;
  48145. }
  48146. return true;
  48147. }
  48148. if (this._localDelayOffset === null) {
  48149. this._localDelayOffset = delay;
  48150. this._pausedDelay = null;
  48151. }
  48152. else if (this._pausedDelay !== null) {
  48153. this._localDelayOffset += delay - this._pausedDelay;
  48154. this._pausedDelay = null;
  48155. }
  48156. // Animating
  48157. var running = false;
  48158. var runtimeAnimations = this._runtimeAnimations;
  48159. var index;
  48160. for (index = 0; index < runtimeAnimations.length; index++) {
  48161. var animation = runtimeAnimations[index];
  48162. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  48163. running = running || isRunning;
  48164. }
  48165. this.animationStarted = running;
  48166. if (!running) {
  48167. // Remove from active animatables
  48168. index = this._scene._activeAnimatables.indexOf(this);
  48169. this._scene._activeAnimatables.splice(index, 1);
  48170. // Dispose all runtime animations
  48171. for (index = 0; index < runtimeAnimations.length; index++) {
  48172. runtimeAnimations[index].dispose();
  48173. }
  48174. }
  48175. if (!running && this.onAnimationEnd) {
  48176. this.onAnimationEnd();
  48177. this.onAnimationEnd = null;
  48178. }
  48179. return running;
  48180. };
  48181. return Animatable;
  48182. }());
  48183. BABYLON.Animatable = Animatable;
  48184. })(BABYLON || (BABYLON = {}));
  48185. //# sourceMappingURL=babylon.animatable.js.map
  48186. var BABYLON;
  48187. (function (BABYLON) {
  48188. var EasingFunction = /** @class */ (function () {
  48189. function EasingFunction() {
  48190. // Properties
  48191. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  48192. }
  48193. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  48194. get: function () {
  48195. return EasingFunction._EASINGMODE_EASEIN;
  48196. },
  48197. enumerable: true,
  48198. configurable: true
  48199. });
  48200. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  48201. get: function () {
  48202. return EasingFunction._EASINGMODE_EASEOUT;
  48203. },
  48204. enumerable: true,
  48205. configurable: true
  48206. });
  48207. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  48208. get: function () {
  48209. return EasingFunction._EASINGMODE_EASEINOUT;
  48210. },
  48211. enumerable: true,
  48212. configurable: true
  48213. });
  48214. EasingFunction.prototype.setEasingMode = function (easingMode) {
  48215. var n = Math.min(Math.max(easingMode, 0), 2);
  48216. this._easingMode = n;
  48217. };
  48218. EasingFunction.prototype.getEasingMode = function () {
  48219. return this._easingMode;
  48220. };
  48221. EasingFunction.prototype.easeInCore = function (gradient) {
  48222. throw new Error('You must implement this method');
  48223. };
  48224. EasingFunction.prototype.ease = function (gradient) {
  48225. switch (this._easingMode) {
  48226. case EasingFunction.EASINGMODE_EASEIN:
  48227. return this.easeInCore(gradient);
  48228. case EasingFunction.EASINGMODE_EASEOUT:
  48229. return (1 - this.easeInCore(1 - gradient));
  48230. }
  48231. if (gradient >= 0.5) {
  48232. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  48233. }
  48234. return (this.easeInCore(gradient * 2) * 0.5);
  48235. };
  48236. //Statics
  48237. EasingFunction._EASINGMODE_EASEIN = 0;
  48238. EasingFunction._EASINGMODE_EASEOUT = 1;
  48239. EasingFunction._EASINGMODE_EASEINOUT = 2;
  48240. return EasingFunction;
  48241. }());
  48242. BABYLON.EasingFunction = EasingFunction;
  48243. var CircleEase = /** @class */ (function (_super) {
  48244. __extends(CircleEase, _super);
  48245. function CircleEase() {
  48246. return _super !== null && _super.apply(this, arguments) || this;
  48247. }
  48248. CircleEase.prototype.easeInCore = function (gradient) {
  48249. gradient = Math.max(0, Math.min(1, gradient));
  48250. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  48251. };
  48252. return CircleEase;
  48253. }(EasingFunction));
  48254. BABYLON.CircleEase = CircleEase;
  48255. var BackEase = /** @class */ (function (_super) {
  48256. __extends(BackEase, _super);
  48257. function BackEase(amplitude) {
  48258. if (amplitude === void 0) { amplitude = 1; }
  48259. var _this = _super.call(this) || this;
  48260. _this.amplitude = amplitude;
  48261. return _this;
  48262. }
  48263. BackEase.prototype.easeInCore = function (gradient) {
  48264. var num = Math.max(0, this.amplitude);
  48265. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  48266. };
  48267. return BackEase;
  48268. }(EasingFunction));
  48269. BABYLON.BackEase = BackEase;
  48270. var BounceEase = /** @class */ (function (_super) {
  48271. __extends(BounceEase, _super);
  48272. function BounceEase(bounces, bounciness) {
  48273. if (bounces === void 0) { bounces = 3; }
  48274. if (bounciness === void 0) { bounciness = 2; }
  48275. var _this = _super.call(this) || this;
  48276. _this.bounces = bounces;
  48277. _this.bounciness = bounciness;
  48278. return _this;
  48279. }
  48280. BounceEase.prototype.easeInCore = function (gradient) {
  48281. var y = Math.max(0.0, this.bounces);
  48282. var bounciness = this.bounciness;
  48283. if (bounciness <= 1.0) {
  48284. bounciness = 1.001;
  48285. }
  48286. var num9 = Math.pow(bounciness, y);
  48287. var num5 = 1.0 - bounciness;
  48288. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  48289. var num15 = gradient * num4;
  48290. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  48291. var num3 = Math.floor(num65);
  48292. var num13 = num3 + 1.0;
  48293. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  48294. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  48295. var num7 = (num8 + num12) * 0.5;
  48296. var num6 = gradient - num7;
  48297. var num2 = num7 - num8;
  48298. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  48299. };
  48300. return BounceEase;
  48301. }(EasingFunction));
  48302. BABYLON.BounceEase = BounceEase;
  48303. var CubicEase = /** @class */ (function (_super) {
  48304. __extends(CubicEase, _super);
  48305. function CubicEase() {
  48306. return _super !== null && _super.apply(this, arguments) || this;
  48307. }
  48308. CubicEase.prototype.easeInCore = function (gradient) {
  48309. return (gradient * gradient * gradient);
  48310. };
  48311. return CubicEase;
  48312. }(EasingFunction));
  48313. BABYLON.CubicEase = CubicEase;
  48314. var ElasticEase = /** @class */ (function (_super) {
  48315. __extends(ElasticEase, _super);
  48316. function ElasticEase(oscillations, springiness) {
  48317. if (oscillations === void 0) { oscillations = 3; }
  48318. if (springiness === void 0) { springiness = 3; }
  48319. var _this = _super.call(this) || this;
  48320. _this.oscillations = oscillations;
  48321. _this.springiness = springiness;
  48322. return _this;
  48323. }
  48324. ElasticEase.prototype.easeInCore = function (gradient) {
  48325. var num2;
  48326. var num3 = Math.max(0.0, this.oscillations);
  48327. var num = Math.max(0.0, this.springiness);
  48328. if (num == 0) {
  48329. num2 = gradient;
  48330. }
  48331. else {
  48332. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  48333. }
  48334. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  48335. };
  48336. return ElasticEase;
  48337. }(EasingFunction));
  48338. BABYLON.ElasticEase = ElasticEase;
  48339. var ExponentialEase = /** @class */ (function (_super) {
  48340. __extends(ExponentialEase, _super);
  48341. function ExponentialEase(exponent) {
  48342. if (exponent === void 0) { exponent = 2; }
  48343. var _this = _super.call(this) || this;
  48344. _this.exponent = exponent;
  48345. return _this;
  48346. }
  48347. ExponentialEase.prototype.easeInCore = function (gradient) {
  48348. if (this.exponent <= 0) {
  48349. return gradient;
  48350. }
  48351. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  48352. };
  48353. return ExponentialEase;
  48354. }(EasingFunction));
  48355. BABYLON.ExponentialEase = ExponentialEase;
  48356. var PowerEase = /** @class */ (function (_super) {
  48357. __extends(PowerEase, _super);
  48358. function PowerEase(power) {
  48359. if (power === void 0) { power = 2; }
  48360. var _this = _super.call(this) || this;
  48361. _this.power = power;
  48362. return _this;
  48363. }
  48364. PowerEase.prototype.easeInCore = function (gradient) {
  48365. var y = Math.max(0.0, this.power);
  48366. return Math.pow(gradient, y);
  48367. };
  48368. return PowerEase;
  48369. }(EasingFunction));
  48370. BABYLON.PowerEase = PowerEase;
  48371. var QuadraticEase = /** @class */ (function (_super) {
  48372. __extends(QuadraticEase, _super);
  48373. function QuadraticEase() {
  48374. return _super !== null && _super.apply(this, arguments) || this;
  48375. }
  48376. QuadraticEase.prototype.easeInCore = function (gradient) {
  48377. return (gradient * gradient);
  48378. };
  48379. return QuadraticEase;
  48380. }(EasingFunction));
  48381. BABYLON.QuadraticEase = QuadraticEase;
  48382. var QuarticEase = /** @class */ (function (_super) {
  48383. __extends(QuarticEase, _super);
  48384. function QuarticEase() {
  48385. return _super !== null && _super.apply(this, arguments) || this;
  48386. }
  48387. QuarticEase.prototype.easeInCore = function (gradient) {
  48388. return (gradient * gradient * gradient * gradient);
  48389. };
  48390. return QuarticEase;
  48391. }(EasingFunction));
  48392. BABYLON.QuarticEase = QuarticEase;
  48393. var QuinticEase = /** @class */ (function (_super) {
  48394. __extends(QuinticEase, _super);
  48395. function QuinticEase() {
  48396. return _super !== null && _super.apply(this, arguments) || this;
  48397. }
  48398. QuinticEase.prototype.easeInCore = function (gradient) {
  48399. return (gradient * gradient * gradient * gradient * gradient);
  48400. };
  48401. return QuinticEase;
  48402. }(EasingFunction));
  48403. BABYLON.QuinticEase = QuinticEase;
  48404. var SineEase = /** @class */ (function (_super) {
  48405. __extends(SineEase, _super);
  48406. function SineEase() {
  48407. return _super !== null && _super.apply(this, arguments) || this;
  48408. }
  48409. SineEase.prototype.easeInCore = function (gradient) {
  48410. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  48411. };
  48412. return SineEase;
  48413. }(EasingFunction));
  48414. BABYLON.SineEase = SineEase;
  48415. var BezierCurveEase = /** @class */ (function (_super) {
  48416. __extends(BezierCurveEase, _super);
  48417. function BezierCurveEase(x1, y1, x2, y2) {
  48418. if (x1 === void 0) { x1 = 0; }
  48419. if (y1 === void 0) { y1 = 0; }
  48420. if (x2 === void 0) { x2 = 1; }
  48421. if (y2 === void 0) { y2 = 1; }
  48422. var _this = _super.call(this) || this;
  48423. _this.x1 = x1;
  48424. _this.y1 = y1;
  48425. _this.x2 = x2;
  48426. _this.y2 = y2;
  48427. return _this;
  48428. }
  48429. BezierCurveEase.prototype.easeInCore = function (gradient) {
  48430. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  48431. };
  48432. return BezierCurveEase;
  48433. }(EasingFunction));
  48434. BABYLON.BezierCurveEase = BezierCurveEase;
  48435. })(BABYLON || (BABYLON = {}));
  48436. //# sourceMappingURL=babylon.easing.js.map
  48437. var BABYLON;
  48438. (function (BABYLON) {
  48439. var Condition = /** @class */ (function () {
  48440. function Condition(actionManager) {
  48441. this._actionManager = actionManager;
  48442. }
  48443. Condition.prototype.isValid = function () {
  48444. return true;
  48445. };
  48446. Condition.prototype._getProperty = function (propertyPath) {
  48447. return this._actionManager._getProperty(propertyPath);
  48448. };
  48449. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  48450. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48451. };
  48452. Condition.prototype.serialize = function () {
  48453. };
  48454. Condition.prototype._serialize = function (serializedCondition) {
  48455. return {
  48456. type: 2,
  48457. children: [],
  48458. name: serializedCondition.name,
  48459. properties: serializedCondition.properties
  48460. };
  48461. };
  48462. return Condition;
  48463. }());
  48464. BABYLON.Condition = Condition;
  48465. var ValueCondition = /** @class */ (function (_super) {
  48466. __extends(ValueCondition, _super);
  48467. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  48468. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  48469. var _this = _super.call(this, actionManager) || this;
  48470. _this.propertyPath = propertyPath;
  48471. _this.value = value;
  48472. _this.operator = operator;
  48473. _this._target = target;
  48474. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  48475. _this._property = _this._getProperty(_this.propertyPath);
  48476. return _this;
  48477. }
  48478. Object.defineProperty(ValueCondition, "IsEqual", {
  48479. get: function () {
  48480. return ValueCondition._IsEqual;
  48481. },
  48482. enumerable: true,
  48483. configurable: true
  48484. });
  48485. Object.defineProperty(ValueCondition, "IsDifferent", {
  48486. get: function () {
  48487. return ValueCondition._IsDifferent;
  48488. },
  48489. enumerable: true,
  48490. configurable: true
  48491. });
  48492. Object.defineProperty(ValueCondition, "IsGreater", {
  48493. get: function () {
  48494. return ValueCondition._IsGreater;
  48495. },
  48496. enumerable: true,
  48497. configurable: true
  48498. });
  48499. Object.defineProperty(ValueCondition, "IsLesser", {
  48500. get: function () {
  48501. return ValueCondition._IsLesser;
  48502. },
  48503. enumerable: true,
  48504. configurable: true
  48505. });
  48506. // Methods
  48507. ValueCondition.prototype.isValid = function () {
  48508. switch (this.operator) {
  48509. case ValueCondition.IsGreater:
  48510. return this._effectiveTarget[this._property] > this.value;
  48511. case ValueCondition.IsLesser:
  48512. return this._effectiveTarget[this._property] < this.value;
  48513. case ValueCondition.IsEqual:
  48514. case ValueCondition.IsDifferent:
  48515. var check;
  48516. if (this.value.equals) {
  48517. check = this.value.equals(this._effectiveTarget[this._property]);
  48518. }
  48519. else {
  48520. check = this.value === this._effectiveTarget[this._property];
  48521. }
  48522. return this.operator === ValueCondition.IsEqual ? check : !check;
  48523. }
  48524. return false;
  48525. };
  48526. ValueCondition.prototype.serialize = function () {
  48527. return this._serialize({
  48528. name: "ValueCondition",
  48529. properties: [
  48530. BABYLON.Action._GetTargetProperty(this._target),
  48531. { name: "propertyPath", value: this.propertyPath },
  48532. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48533. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  48534. ]
  48535. });
  48536. };
  48537. ValueCondition.GetOperatorName = function (operator) {
  48538. switch (operator) {
  48539. case ValueCondition._IsEqual: return "IsEqual";
  48540. case ValueCondition._IsDifferent: return "IsDifferent";
  48541. case ValueCondition._IsGreater: return "IsGreater";
  48542. case ValueCondition._IsLesser: return "IsLesser";
  48543. default: return "";
  48544. }
  48545. };
  48546. // Statics
  48547. ValueCondition._IsEqual = 0;
  48548. ValueCondition._IsDifferent = 1;
  48549. ValueCondition._IsGreater = 2;
  48550. ValueCondition._IsLesser = 3;
  48551. return ValueCondition;
  48552. }(Condition));
  48553. BABYLON.ValueCondition = ValueCondition;
  48554. var PredicateCondition = /** @class */ (function (_super) {
  48555. __extends(PredicateCondition, _super);
  48556. function PredicateCondition(actionManager, predicate) {
  48557. var _this = _super.call(this, actionManager) || this;
  48558. _this.predicate = predicate;
  48559. return _this;
  48560. }
  48561. PredicateCondition.prototype.isValid = function () {
  48562. return this.predicate();
  48563. };
  48564. return PredicateCondition;
  48565. }(Condition));
  48566. BABYLON.PredicateCondition = PredicateCondition;
  48567. var StateCondition = /** @class */ (function (_super) {
  48568. __extends(StateCondition, _super);
  48569. function StateCondition(actionManager, target, value) {
  48570. var _this = _super.call(this, actionManager) || this;
  48571. _this.value = value;
  48572. _this._target = target;
  48573. return _this;
  48574. }
  48575. // Methods
  48576. StateCondition.prototype.isValid = function () {
  48577. return this._target.state === this.value;
  48578. };
  48579. StateCondition.prototype.serialize = function () {
  48580. return this._serialize({
  48581. name: "StateCondition",
  48582. properties: [
  48583. BABYLON.Action._GetTargetProperty(this._target),
  48584. { name: "value", value: this.value }
  48585. ]
  48586. });
  48587. };
  48588. return StateCondition;
  48589. }(Condition));
  48590. BABYLON.StateCondition = StateCondition;
  48591. })(BABYLON || (BABYLON = {}));
  48592. //# sourceMappingURL=babylon.condition.js.map
  48593. var BABYLON;
  48594. (function (BABYLON) {
  48595. var Action = /** @class */ (function () {
  48596. function Action(triggerOptions, condition) {
  48597. this.triggerOptions = triggerOptions;
  48598. this.onBeforeExecuteObservable = new BABYLON.Observable();
  48599. if (triggerOptions.parameter) {
  48600. this.trigger = triggerOptions.trigger;
  48601. this._triggerParameter = triggerOptions.parameter;
  48602. }
  48603. else {
  48604. this.trigger = triggerOptions;
  48605. }
  48606. this._nextActiveAction = this;
  48607. this._condition = condition;
  48608. }
  48609. // Methods
  48610. Action.prototype._prepare = function () {
  48611. };
  48612. Action.prototype.getTriggerParameter = function () {
  48613. return this._triggerParameter;
  48614. };
  48615. Action.prototype._executeCurrent = function (evt) {
  48616. if (this._nextActiveAction._condition) {
  48617. var condition = this._nextActiveAction._condition;
  48618. var currentRenderId = this._actionManager.getScene().getRenderId();
  48619. // We cache the current evaluation for the current frame
  48620. if (condition._evaluationId === currentRenderId) {
  48621. if (!condition._currentResult) {
  48622. return;
  48623. }
  48624. }
  48625. else {
  48626. condition._evaluationId = currentRenderId;
  48627. if (!condition.isValid()) {
  48628. condition._currentResult = false;
  48629. return;
  48630. }
  48631. condition._currentResult = true;
  48632. }
  48633. }
  48634. this.onBeforeExecuteObservable.notifyObservers(this);
  48635. this._nextActiveAction.execute(evt);
  48636. this.skipToNextActiveAction();
  48637. };
  48638. Action.prototype.execute = function (evt) {
  48639. };
  48640. Action.prototype.skipToNextActiveAction = function () {
  48641. if (this._nextActiveAction._child) {
  48642. if (!this._nextActiveAction._child._actionManager) {
  48643. this._nextActiveAction._child._actionManager = this._actionManager;
  48644. }
  48645. this._nextActiveAction = this._nextActiveAction._child;
  48646. }
  48647. else {
  48648. this._nextActiveAction = this;
  48649. }
  48650. };
  48651. Action.prototype.then = function (action) {
  48652. this._child = action;
  48653. action._actionManager = this._actionManager;
  48654. action._prepare();
  48655. return action;
  48656. };
  48657. Action.prototype._getProperty = function (propertyPath) {
  48658. return this._actionManager._getProperty(propertyPath);
  48659. };
  48660. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  48661. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48662. };
  48663. Action.prototype.serialize = function (parent) {
  48664. };
  48665. // Called by BABYLON.Action objects in serialize(...). Internal use
  48666. Action.prototype._serialize = function (serializedAction, parent) {
  48667. var serializationObject = {
  48668. type: 1,
  48669. children: [],
  48670. name: serializedAction.name,
  48671. properties: serializedAction.properties || []
  48672. };
  48673. // Serialize child
  48674. if (this._child) {
  48675. this._child.serialize(serializationObject);
  48676. }
  48677. // Check if "this" has a condition
  48678. if (this._condition) {
  48679. var serializedCondition = this._condition.serialize();
  48680. serializedCondition.children.push(serializationObject);
  48681. if (parent) {
  48682. parent.children.push(serializedCondition);
  48683. }
  48684. return serializedCondition;
  48685. }
  48686. if (parent) {
  48687. parent.children.push(serializationObject);
  48688. }
  48689. return serializationObject;
  48690. };
  48691. Action._SerializeValueAsString = function (value) {
  48692. if (typeof value === "number") {
  48693. return value.toString();
  48694. }
  48695. if (typeof value === "boolean") {
  48696. return value ? "true" : "false";
  48697. }
  48698. if (value instanceof BABYLON.Vector2) {
  48699. return value.x + ", " + value.y;
  48700. }
  48701. if (value instanceof BABYLON.Vector3) {
  48702. return value.x + ", " + value.y + ", " + value.z;
  48703. }
  48704. if (value instanceof BABYLON.Color3) {
  48705. return value.r + ", " + value.g + ", " + value.b;
  48706. }
  48707. if (value instanceof BABYLON.Color4) {
  48708. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  48709. }
  48710. return value; // string
  48711. };
  48712. Action._GetTargetProperty = function (target) {
  48713. return {
  48714. name: "target",
  48715. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  48716. : target instanceof BABYLON.Light ? "LightProperties"
  48717. : target instanceof BABYLON.Camera ? "CameraProperties"
  48718. : "SceneProperties",
  48719. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  48720. };
  48721. };
  48722. return Action;
  48723. }());
  48724. BABYLON.Action = Action;
  48725. })(BABYLON || (BABYLON = {}));
  48726. //# sourceMappingURL=babylon.action.js.map
  48727. var BABYLON;
  48728. (function (BABYLON) {
  48729. /**
  48730. * ActionEvent is the event beint sent when an action is triggered.
  48731. */
  48732. var ActionEvent = /** @class */ (function () {
  48733. /**
  48734. * @param source The mesh or sprite that triggered the action.
  48735. * @param pointerX The X mouse cursor position at the time of the event
  48736. * @param pointerY The Y mouse cursor position at the time of the event
  48737. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  48738. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  48739. */
  48740. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  48741. this.source = source;
  48742. this.pointerX = pointerX;
  48743. this.pointerY = pointerY;
  48744. this.meshUnderPointer = meshUnderPointer;
  48745. this.sourceEvent = sourceEvent;
  48746. this.additionalData = additionalData;
  48747. }
  48748. /**
  48749. * Helper function to auto-create an ActionEvent from a source mesh.
  48750. * @param source The source mesh that triggered the event
  48751. * @param evt {Event} The original (browser) event
  48752. */
  48753. ActionEvent.CreateNew = function (source, evt, additionalData) {
  48754. var scene = source.getScene();
  48755. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48756. };
  48757. /**
  48758. * Helper function to auto-create an ActionEvent from a source mesh.
  48759. * @param source The source sprite that triggered the event
  48760. * @param scene Scene associated with the sprite
  48761. * @param evt {Event} The original (browser) event
  48762. */
  48763. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  48764. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48765. };
  48766. /**
  48767. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  48768. * @param scene the scene where the event occurred
  48769. * @param evt {Event} The original (browser) event
  48770. */
  48771. ActionEvent.CreateNewFromScene = function (scene, evt) {
  48772. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  48773. };
  48774. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  48775. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  48776. };
  48777. return ActionEvent;
  48778. }());
  48779. BABYLON.ActionEvent = ActionEvent;
  48780. /**
  48781. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  48782. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  48783. */
  48784. var ActionManager = /** @class */ (function () {
  48785. function ActionManager(scene) {
  48786. // Members
  48787. this.actions = new Array();
  48788. this.hoverCursor = '';
  48789. this._scene = scene;
  48790. scene._actionManagers.push(this);
  48791. }
  48792. Object.defineProperty(ActionManager, "NothingTrigger", {
  48793. get: function () {
  48794. return ActionManager._NothingTrigger;
  48795. },
  48796. enumerable: true,
  48797. configurable: true
  48798. });
  48799. Object.defineProperty(ActionManager, "OnPickTrigger", {
  48800. get: function () {
  48801. return ActionManager._OnPickTrigger;
  48802. },
  48803. enumerable: true,
  48804. configurable: true
  48805. });
  48806. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  48807. get: function () {
  48808. return ActionManager._OnLeftPickTrigger;
  48809. },
  48810. enumerable: true,
  48811. configurable: true
  48812. });
  48813. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  48814. get: function () {
  48815. return ActionManager._OnRightPickTrigger;
  48816. },
  48817. enumerable: true,
  48818. configurable: true
  48819. });
  48820. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  48821. get: function () {
  48822. return ActionManager._OnCenterPickTrigger;
  48823. },
  48824. enumerable: true,
  48825. configurable: true
  48826. });
  48827. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  48828. get: function () {
  48829. return ActionManager._OnPickDownTrigger;
  48830. },
  48831. enumerable: true,
  48832. configurable: true
  48833. });
  48834. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  48835. get: function () {
  48836. return ActionManager._OnDoublePickTrigger;
  48837. },
  48838. enumerable: true,
  48839. configurable: true
  48840. });
  48841. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  48842. get: function () {
  48843. return ActionManager._OnPickUpTrigger;
  48844. },
  48845. enumerable: true,
  48846. configurable: true
  48847. });
  48848. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  48849. /// This trigger will only be raised if you also declared a OnPickDown
  48850. get: function () {
  48851. return ActionManager._OnPickOutTrigger;
  48852. },
  48853. enumerable: true,
  48854. configurable: true
  48855. });
  48856. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  48857. get: function () {
  48858. return ActionManager._OnLongPressTrigger;
  48859. },
  48860. enumerable: true,
  48861. configurable: true
  48862. });
  48863. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  48864. get: function () {
  48865. return ActionManager._OnPointerOverTrigger;
  48866. },
  48867. enumerable: true,
  48868. configurable: true
  48869. });
  48870. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  48871. get: function () {
  48872. return ActionManager._OnPointerOutTrigger;
  48873. },
  48874. enumerable: true,
  48875. configurable: true
  48876. });
  48877. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  48878. get: function () {
  48879. return ActionManager._OnEveryFrameTrigger;
  48880. },
  48881. enumerable: true,
  48882. configurable: true
  48883. });
  48884. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  48885. get: function () {
  48886. return ActionManager._OnIntersectionEnterTrigger;
  48887. },
  48888. enumerable: true,
  48889. configurable: true
  48890. });
  48891. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  48892. get: function () {
  48893. return ActionManager._OnIntersectionExitTrigger;
  48894. },
  48895. enumerable: true,
  48896. configurable: true
  48897. });
  48898. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  48899. get: function () {
  48900. return ActionManager._OnKeyDownTrigger;
  48901. },
  48902. enumerable: true,
  48903. configurable: true
  48904. });
  48905. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  48906. get: function () {
  48907. return ActionManager._OnKeyUpTrigger;
  48908. },
  48909. enumerable: true,
  48910. configurable: true
  48911. });
  48912. // Methods
  48913. ActionManager.prototype.dispose = function () {
  48914. var index = this._scene._actionManagers.indexOf(this);
  48915. for (var i = 0; i < this.actions.length; i++) {
  48916. var action = this.actions[i];
  48917. ActionManager.Triggers[action.trigger]--;
  48918. if (ActionManager.Triggers[action.trigger] === 0) {
  48919. delete ActionManager.Triggers[action.trigger];
  48920. }
  48921. }
  48922. if (index > -1) {
  48923. this._scene._actionManagers.splice(index, 1);
  48924. }
  48925. };
  48926. ActionManager.prototype.getScene = function () {
  48927. return this._scene;
  48928. };
  48929. /**
  48930. * Does this action manager handles actions of any of the given triggers
  48931. * @param {number[]} triggers - the triggers to be tested
  48932. * @return {boolean} whether one (or more) of the triggers is handeled
  48933. */
  48934. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  48935. for (var index = 0; index < this.actions.length; index++) {
  48936. var action = this.actions[index];
  48937. if (triggers.indexOf(action.trigger) > -1) {
  48938. return true;
  48939. }
  48940. }
  48941. return false;
  48942. };
  48943. /**
  48944. * Does this action manager handles actions of a given trigger
  48945. * @param {number} trigger - the trigger to be tested
  48946. * @return {boolean} whether the trigger is handeled
  48947. */
  48948. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  48949. for (var index = 0; index < this.actions.length; index++) {
  48950. var action = this.actions[index];
  48951. if (action.trigger === trigger) {
  48952. return true;
  48953. }
  48954. }
  48955. return false;
  48956. };
  48957. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  48958. /**
  48959. * Does this action manager has pointer triggers
  48960. * @return {boolean} whether or not it has pointer triggers
  48961. */
  48962. get: function () {
  48963. for (var index = 0; index < this.actions.length; index++) {
  48964. var action = this.actions[index];
  48965. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  48966. return true;
  48967. }
  48968. }
  48969. return false;
  48970. },
  48971. enumerable: true,
  48972. configurable: true
  48973. });
  48974. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  48975. /**
  48976. * Does this action manager has pick triggers
  48977. * @return {boolean} whether or not it has pick triggers
  48978. */
  48979. get: function () {
  48980. for (var index = 0; index < this.actions.length; index++) {
  48981. var action = this.actions[index];
  48982. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  48983. return true;
  48984. }
  48985. }
  48986. return false;
  48987. },
  48988. enumerable: true,
  48989. configurable: true
  48990. });
  48991. Object.defineProperty(ActionManager, "HasTriggers", {
  48992. /**
  48993. * Does exist one action manager with at least one trigger
  48994. * @return {boolean} whether or not it exists one action manager with one trigger
  48995. **/
  48996. get: function () {
  48997. for (var t in ActionManager.Triggers) {
  48998. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48999. return true;
  49000. }
  49001. }
  49002. return false;
  49003. },
  49004. enumerable: true,
  49005. configurable: true
  49006. });
  49007. Object.defineProperty(ActionManager, "HasPickTriggers", {
  49008. /**
  49009. * Does exist one action manager with at least one pick trigger
  49010. * @return {boolean} whether or not it exists one action manager with one pick trigger
  49011. **/
  49012. get: function () {
  49013. for (var t in ActionManager.Triggers) {
  49014. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49015. var t_int = parseInt(t);
  49016. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  49017. return true;
  49018. }
  49019. }
  49020. }
  49021. return false;
  49022. },
  49023. enumerable: true,
  49024. configurable: true
  49025. });
  49026. /**
  49027. * Does exist one action manager that handles actions of a given trigger
  49028. * @param {number} trigger - the trigger to be tested
  49029. * @return {boolean} whether the trigger is handeled by at least one action manager
  49030. **/
  49031. ActionManager.HasSpecificTrigger = function (trigger) {
  49032. for (var t in ActionManager.Triggers) {
  49033. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49034. var t_int = parseInt(t);
  49035. if (t_int === trigger) {
  49036. return true;
  49037. }
  49038. }
  49039. }
  49040. return false;
  49041. };
  49042. /**
  49043. * Registers an action to this action manager
  49044. * @param {BABYLON.Action} action - the action to be registered
  49045. * @return {BABYLON.Action} the action amended (prepared) after registration
  49046. */
  49047. ActionManager.prototype.registerAction = function (action) {
  49048. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  49049. if (this.getScene().actionManager !== this) {
  49050. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  49051. return null;
  49052. }
  49053. }
  49054. this.actions.push(action);
  49055. if (ActionManager.Triggers[action.trigger]) {
  49056. ActionManager.Triggers[action.trigger]++;
  49057. }
  49058. else {
  49059. ActionManager.Triggers[action.trigger] = 1;
  49060. }
  49061. action._actionManager = this;
  49062. action._prepare();
  49063. return action;
  49064. };
  49065. /**
  49066. * Unregisters an action to this action manager
  49067. * @param action The action to be unregistered
  49068. * @return whether the action has been unregistered
  49069. */
  49070. ActionManager.prototype.unregisterAction = function (action) {
  49071. var index = this.actions.indexOf(action);
  49072. if (index !== -1) {
  49073. this.actions.splice(index, 1);
  49074. ActionManager.Triggers[action.trigger] -= 1;
  49075. if (ActionManager.Triggers[action.trigger] === 0) {
  49076. delete ActionManager.Triggers[action.trigger];
  49077. }
  49078. delete action._actionManager;
  49079. return true;
  49080. }
  49081. return false;
  49082. };
  49083. /**
  49084. * Process a specific trigger
  49085. * @param {number} trigger - the trigger to process
  49086. * @param evt {BABYLON.ActionEvent} the event details to be processed
  49087. */
  49088. ActionManager.prototype.processTrigger = function (trigger, evt) {
  49089. for (var index = 0; index < this.actions.length; index++) {
  49090. var action = this.actions[index];
  49091. if (action.trigger === trigger) {
  49092. if (evt) {
  49093. if (trigger === ActionManager.OnKeyUpTrigger
  49094. || trigger === ActionManager.OnKeyDownTrigger) {
  49095. var parameter = action.getTriggerParameter();
  49096. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  49097. if (!parameter.toLowerCase) {
  49098. continue;
  49099. }
  49100. var lowerCase = parameter.toLowerCase();
  49101. if (lowerCase !== evt.sourceEvent.key) {
  49102. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  49103. var actualkey = String.fromCharCode(unicode).toLowerCase();
  49104. if (actualkey !== lowerCase) {
  49105. continue;
  49106. }
  49107. }
  49108. }
  49109. }
  49110. }
  49111. action._executeCurrent(evt);
  49112. }
  49113. }
  49114. };
  49115. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  49116. var properties = propertyPath.split(".");
  49117. for (var index = 0; index < properties.length - 1; index++) {
  49118. target = target[properties[index]];
  49119. }
  49120. return target;
  49121. };
  49122. ActionManager.prototype._getProperty = function (propertyPath) {
  49123. var properties = propertyPath.split(".");
  49124. return properties[properties.length - 1];
  49125. };
  49126. ActionManager.prototype.serialize = function (name) {
  49127. var root = {
  49128. children: new Array(),
  49129. name: name,
  49130. type: 3,
  49131. properties: new Array() // Empty for root but required
  49132. };
  49133. for (var i = 0; i < this.actions.length; i++) {
  49134. var triggerObject = {
  49135. type: 0,
  49136. children: new Array(),
  49137. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  49138. properties: new Array()
  49139. };
  49140. var triggerOptions = this.actions[i].triggerOptions;
  49141. if (triggerOptions && typeof triggerOptions !== "number") {
  49142. if (triggerOptions.parameter instanceof BABYLON.Node) {
  49143. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  49144. }
  49145. else {
  49146. var parameter = {};
  49147. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  49148. if (triggerOptions.parameter.mesh) {
  49149. parameter._meshId = triggerOptions.parameter.mesh.id;
  49150. }
  49151. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  49152. }
  49153. }
  49154. // Serialize child action, recursively
  49155. this.actions[i].serialize(triggerObject);
  49156. // Add serialized trigger
  49157. root.children.push(triggerObject);
  49158. }
  49159. return root;
  49160. };
  49161. ActionManager.Parse = function (parsedActions, object, scene) {
  49162. var actionManager = new ActionManager(scene);
  49163. if (object === null)
  49164. scene.actionManager = actionManager;
  49165. else
  49166. object.actionManager = actionManager;
  49167. // instanciate a new object
  49168. var instanciate = function (name, params) {
  49169. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  49170. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  49171. newInstance.constructor.apply(newInstance, params);
  49172. return newInstance;
  49173. };
  49174. var parseParameter = function (name, value, target, propertyPath) {
  49175. if (propertyPath === null) {
  49176. // String, boolean or float
  49177. var floatValue = parseFloat(value);
  49178. if (value === "true" || value === "false")
  49179. return value === "true";
  49180. else
  49181. return isNaN(floatValue) ? value : floatValue;
  49182. }
  49183. var effectiveTarget = propertyPath.split(".");
  49184. var values = value.split(",");
  49185. // Get effective Target
  49186. for (var i = 0; i < effectiveTarget.length; i++) {
  49187. target = target[effectiveTarget[i]];
  49188. }
  49189. // Return appropriate value with its type
  49190. if (typeof (target) === "boolean")
  49191. return values[0] === "true";
  49192. if (typeof (target) === "string")
  49193. return values[0];
  49194. // Parameters with multiple values such as Vector3 etc.
  49195. var split = new Array();
  49196. for (var i = 0; i < values.length; i++)
  49197. split.push(parseFloat(values[i]));
  49198. if (target instanceof BABYLON.Vector3)
  49199. return BABYLON.Vector3.FromArray(split);
  49200. if (target instanceof BABYLON.Vector4)
  49201. return BABYLON.Vector4.FromArray(split);
  49202. if (target instanceof BABYLON.Color3)
  49203. return BABYLON.Color3.FromArray(split);
  49204. if (target instanceof BABYLON.Color4)
  49205. return BABYLON.Color4.FromArray(split);
  49206. return parseFloat(values[0]);
  49207. };
  49208. // traverse graph per trigger
  49209. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  49210. if (combineArray === void 0) { combineArray = null; }
  49211. if (parsedAction.detached)
  49212. return;
  49213. var parameters = new Array();
  49214. var target = null;
  49215. var propertyPath = null;
  49216. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  49217. // Parameters
  49218. if (parsedAction.type === 2)
  49219. parameters.push(actionManager);
  49220. else
  49221. parameters.push(trigger);
  49222. if (combine) {
  49223. var actions = new Array();
  49224. for (var j = 0; j < parsedAction.combine.length; j++) {
  49225. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  49226. }
  49227. parameters.push(actions);
  49228. }
  49229. else {
  49230. for (var i = 0; i < parsedAction.properties.length; i++) {
  49231. var value = parsedAction.properties[i].value;
  49232. var name = parsedAction.properties[i].name;
  49233. var targetType = parsedAction.properties[i].targetType;
  49234. if (name === "target")
  49235. if (targetType !== null && targetType === "SceneProperties")
  49236. value = target = scene;
  49237. else
  49238. value = target = scene.getNodeByName(value);
  49239. else if (name === "parent")
  49240. value = scene.getNodeByName(value);
  49241. else if (name === "sound")
  49242. value = scene.getSoundByName(value);
  49243. else if (name !== "propertyPath") {
  49244. if (parsedAction.type === 2 && name === "operator")
  49245. value = BABYLON.ValueCondition[value];
  49246. else
  49247. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  49248. }
  49249. else {
  49250. propertyPath = value;
  49251. }
  49252. parameters.push(value);
  49253. }
  49254. }
  49255. if (combineArray === null) {
  49256. parameters.push(condition);
  49257. }
  49258. else {
  49259. parameters.push(null);
  49260. }
  49261. // If interpolate value action
  49262. if (parsedAction.name === "InterpolateValueAction") {
  49263. var param = parameters[parameters.length - 2];
  49264. parameters[parameters.length - 1] = param;
  49265. parameters[parameters.length - 2] = condition;
  49266. }
  49267. // Action or condition(s) and not CombineAction
  49268. var newAction = instanciate(parsedAction.name, parameters);
  49269. if (newAction instanceof BABYLON.Condition && condition !== null) {
  49270. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  49271. if (action)
  49272. action.then(nothing);
  49273. else
  49274. actionManager.registerAction(nothing);
  49275. action = nothing;
  49276. }
  49277. if (combineArray === null) {
  49278. if (newAction instanceof BABYLON.Condition) {
  49279. condition = newAction;
  49280. newAction = action;
  49281. }
  49282. else {
  49283. condition = null;
  49284. if (action)
  49285. action.then(newAction);
  49286. else
  49287. actionManager.registerAction(newAction);
  49288. }
  49289. }
  49290. else {
  49291. combineArray.push(newAction);
  49292. }
  49293. for (var i = 0; i < parsedAction.children.length; i++)
  49294. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  49295. };
  49296. // triggers
  49297. for (var i = 0; i < parsedActions.children.length; i++) {
  49298. var triggerParams;
  49299. var trigger = parsedActions.children[i];
  49300. if (trigger.properties.length > 0) {
  49301. var param = trigger.properties[0].value;
  49302. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  49303. if (value._meshId) {
  49304. value.mesh = scene.getMeshByID(value._meshId);
  49305. }
  49306. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  49307. }
  49308. else
  49309. triggerParams = ActionManager[trigger.name];
  49310. for (var j = 0; j < trigger.children.length; j++) {
  49311. if (!trigger.detached)
  49312. traverse(trigger.children[j], triggerParams, null, null);
  49313. }
  49314. }
  49315. };
  49316. ActionManager.GetTriggerName = function (trigger) {
  49317. switch (trigger) {
  49318. case 0: return "NothingTrigger";
  49319. case 1: return "OnPickTrigger";
  49320. case 2: return "OnLeftPickTrigger";
  49321. case 3: return "OnRightPickTrigger";
  49322. case 4: return "OnCenterPickTrigger";
  49323. case 5: return "OnPickDownTrigger";
  49324. case 6: return "OnPickUpTrigger";
  49325. case 7: return "OnLongPressTrigger";
  49326. case 8: return "OnPointerOverTrigger";
  49327. case 9: return "OnPointerOutTrigger";
  49328. case 10: return "OnEveryFrameTrigger";
  49329. case 11: return "OnIntersectionEnterTrigger";
  49330. case 12: return "OnIntersectionExitTrigger";
  49331. case 13: return "OnKeyDownTrigger";
  49332. case 14: return "OnKeyUpTrigger";
  49333. case 15: return "OnPickOutTrigger";
  49334. default: return "";
  49335. }
  49336. };
  49337. // Statics
  49338. ActionManager._NothingTrigger = 0;
  49339. ActionManager._OnPickTrigger = 1;
  49340. ActionManager._OnLeftPickTrigger = 2;
  49341. ActionManager._OnRightPickTrigger = 3;
  49342. ActionManager._OnCenterPickTrigger = 4;
  49343. ActionManager._OnPickDownTrigger = 5;
  49344. ActionManager._OnDoublePickTrigger = 6;
  49345. ActionManager._OnPickUpTrigger = 7;
  49346. ActionManager._OnLongPressTrigger = 8;
  49347. ActionManager._OnPointerOverTrigger = 9;
  49348. ActionManager._OnPointerOutTrigger = 10;
  49349. ActionManager._OnEveryFrameTrigger = 11;
  49350. ActionManager._OnIntersectionEnterTrigger = 12;
  49351. ActionManager._OnIntersectionExitTrigger = 13;
  49352. ActionManager._OnKeyDownTrigger = 14;
  49353. ActionManager._OnKeyUpTrigger = 15;
  49354. ActionManager._OnPickOutTrigger = 16;
  49355. ActionManager.Triggers = {};
  49356. return ActionManager;
  49357. }());
  49358. BABYLON.ActionManager = ActionManager;
  49359. })(BABYLON || (BABYLON = {}));
  49360. //# sourceMappingURL=babylon.actionManager.js.map
  49361. var BABYLON;
  49362. (function (BABYLON) {
  49363. var InterpolateValueAction = /** @class */ (function (_super) {
  49364. __extends(InterpolateValueAction, _super);
  49365. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  49366. if (duration === void 0) { duration = 1000; }
  49367. var _this = _super.call(this, triggerOptions, condition) || this;
  49368. _this.propertyPath = propertyPath;
  49369. _this.value = value;
  49370. _this.duration = duration;
  49371. _this.stopOtherAnimations = stopOtherAnimations;
  49372. _this.onInterpolationDone = onInterpolationDone;
  49373. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  49374. _this._target = _this._effectiveTarget = target;
  49375. return _this;
  49376. }
  49377. InterpolateValueAction.prototype._prepare = function () {
  49378. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49379. this._property = this._getProperty(this.propertyPath);
  49380. };
  49381. InterpolateValueAction.prototype.execute = function () {
  49382. var _this = this;
  49383. var scene = this._actionManager.getScene();
  49384. var keys = [
  49385. {
  49386. frame: 0,
  49387. value: this._effectiveTarget[this._property]
  49388. }, {
  49389. frame: 100,
  49390. value: this.value
  49391. }
  49392. ];
  49393. var dataType;
  49394. if (typeof this.value === "number") {
  49395. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  49396. }
  49397. else if (this.value instanceof BABYLON.Color3) {
  49398. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  49399. }
  49400. else if (this.value instanceof BABYLON.Vector3) {
  49401. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  49402. }
  49403. else if (this.value instanceof BABYLON.Matrix) {
  49404. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  49405. }
  49406. else if (this.value instanceof BABYLON.Quaternion) {
  49407. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  49408. }
  49409. else {
  49410. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  49411. return;
  49412. }
  49413. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  49414. animation.setKeys(keys);
  49415. if (this.stopOtherAnimations) {
  49416. scene.stopAnimation(this._effectiveTarget);
  49417. }
  49418. var wrapper = function () {
  49419. _this.onInterpolationDoneObservable.notifyObservers(_this);
  49420. if (_this.onInterpolationDone) {
  49421. _this.onInterpolationDone();
  49422. }
  49423. };
  49424. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  49425. };
  49426. InterpolateValueAction.prototype.serialize = function (parent) {
  49427. return _super.prototype._serialize.call(this, {
  49428. name: "InterpolateValueAction",
  49429. properties: [
  49430. BABYLON.Action._GetTargetProperty(this._target),
  49431. { name: "propertyPath", value: this.propertyPath },
  49432. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  49433. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  49434. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  49435. ]
  49436. }, parent);
  49437. };
  49438. return InterpolateValueAction;
  49439. }(BABYLON.Action));
  49440. BABYLON.InterpolateValueAction = InterpolateValueAction;
  49441. })(BABYLON || (BABYLON = {}));
  49442. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  49443. var BABYLON;
  49444. (function (BABYLON) {
  49445. var SwitchBooleanAction = /** @class */ (function (_super) {
  49446. __extends(SwitchBooleanAction, _super);
  49447. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  49448. var _this = _super.call(this, triggerOptions, condition) || this;
  49449. _this.propertyPath = propertyPath;
  49450. _this._target = _this._effectiveTarget = target;
  49451. return _this;
  49452. }
  49453. SwitchBooleanAction.prototype._prepare = function () {
  49454. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49455. this._property = this._getProperty(this.propertyPath);
  49456. };
  49457. SwitchBooleanAction.prototype.execute = function () {
  49458. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  49459. };
  49460. SwitchBooleanAction.prototype.serialize = function (parent) {
  49461. return _super.prototype._serialize.call(this, {
  49462. name: "SwitchBooleanAction",
  49463. properties: [
  49464. BABYLON.Action._GetTargetProperty(this._target),
  49465. { name: "propertyPath", value: this.propertyPath }
  49466. ]
  49467. }, parent);
  49468. };
  49469. return SwitchBooleanAction;
  49470. }(BABYLON.Action));
  49471. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  49472. var SetStateAction = /** @class */ (function (_super) {
  49473. __extends(SetStateAction, _super);
  49474. function SetStateAction(triggerOptions, target, value, condition) {
  49475. var _this = _super.call(this, triggerOptions, condition) || this;
  49476. _this.value = value;
  49477. _this._target = target;
  49478. return _this;
  49479. }
  49480. SetStateAction.prototype.execute = function () {
  49481. this._target.state = this.value;
  49482. };
  49483. SetStateAction.prototype.serialize = function (parent) {
  49484. return _super.prototype._serialize.call(this, {
  49485. name: "SetStateAction",
  49486. properties: [
  49487. BABYLON.Action._GetTargetProperty(this._target),
  49488. { name: "value", value: this.value }
  49489. ]
  49490. }, parent);
  49491. };
  49492. return SetStateAction;
  49493. }(BABYLON.Action));
  49494. BABYLON.SetStateAction = SetStateAction;
  49495. var SetValueAction = /** @class */ (function (_super) {
  49496. __extends(SetValueAction, _super);
  49497. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  49498. var _this = _super.call(this, triggerOptions, condition) || this;
  49499. _this.propertyPath = propertyPath;
  49500. _this.value = value;
  49501. _this._target = _this._effectiveTarget = target;
  49502. return _this;
  49503. }
  49504. SetValueAction.prototype._prepare = function () {
  49505. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49506. this._property = this._getProperty(this.propertyPath);
  49507. };
  49508. SetValueAction.prototype.execute = function () {
  49509. this._effectiveTarget[this._property] = this.value;
  49510. if (this._target.markAsDirty) {
  49511. this._target.markAsDirty(this._property);
  49512. }
  49513. };
  49514. SetValueAction.prototype.serialize = function (parent) {
  49515. return _super.prototype._serialize.call(this, {
  49516. name: "SetValueAction",
  49517. properties: [
  49518. BABYLON.Action._GetTargetProperty(this._target),
  49519. { name: "propertyPath", value: this.propertyPath },
  49520. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49521. ]
  49522. }, parent);
  49523. };
  49524. return SetValueAction;
  49525. }(BABYLON.Action));
  49526. BABYLON.SetValueAction = SetValueAction;
  49527. var IncrementValueAction = /** @class */ (function (_super) {
  49528. __extends(IncrementValueAction, _super);
  49529. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  49530. var _this = _super.call(this, triggerOptions, condition) || this;
  49531. _this.propertyPath = propertyPath;
  49532. _this.value = value;
  49533. _this._target = _this._effectiveTarget = target;
  49534. return _this;
  49535. }
  49536. IncrementValueAction.prototype._prepare = function () {
  49537. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49538. this._property = this._getProperty(this.propertyPath);
  49539. if (typeof this._effectiveTarget[this._property] !== "number") {
  49540. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  49541. }
  49542. };
  49543. IncrementValueAction.prototype.execute = function () {
  49544. this._effectiveTarget[this._property] += this.value;
  49545. if (this._target.markAsDirty) {
  49546. this._target.markAsDirty(this._property);
  49547. }
  49548. };
  49549. IncrementValueAction.prototype.serialize = function (parent) {
  49550. return _super.prototype._serialize.call(this, {
  49551. name: "IncrementValueAction",
  49552. properties: [
  49553. BABYLON.Action._GetTargetProperty(this._target),
  49554. { name: "propertyPath", value: this.propertyPath },
  49555. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49556. ]
  49557. }, parent);
  49558. };
  49559. return IncrementValueAction;
  49560. }(BABYLON.Action));
  49561. BABYLON.IncrementValueAction = IncrementValueAction;
  49562. var PlayAnimationAction = /** @class */ (function (_super) {
  49563. __extends(PlayAnimationAction, _super);
  49564. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  49565. var _this = _super.call(this, triggerOptions, condition) || this;
  49566. _this.from = from;
  49567. _this.to = to;
  49568. _this.loop = loop;
  49569. _this._target = target;
  49570. return _this;
  49571. }
  49572. PlayAnimationAction.prototype._prepare = function () {
  49573. };
  49574. PlayAnimationAction.prototype.execute = function () {
  49575. var scene = this._actionManager.getScene();
  49576. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  49577. };
  49578. PlayAnimationAction.prototype.serialize = function (parent) {
  49579. return _super.prototype._serialize.call(this, {
  49580. name: "PlayAnimationAction",
  49581. properties: [
  49582. BABYLON.Action._GetTargetProperty(this._target),
  49583. { name: "from", value: String(this.from) },
  49584. { name: "to", value: String(this.to) },
  49585. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  49586. ]
  49587. }, parent);
  49588. };
  49589. return PlayAnimationAction;
  49590. }(BABYLON.Action));
  49591. BABYLON.PlayAnimationAction = PlayAnimationAction;
  49592. var StopAnimationAction = /** @class */ (function (_super) {
  49593. __extends(StopAnimationAction, _super);
  49594. function StopAnimationAction(triggerOptions, target, condition) {
  49595. var _this = _super.call(this, triggerOptions, condition) || this;
  49596. _this._target = target;
  49597. return _this;
  49598. }
  49599. StopAnimationAction.prototype._prepare = function () {
  49600. };
  49601. StopAnimationAction.prototype.execute = function () {
  49602. var scene = this._actionManager.getScene();
  49603. scene.stopAnimation(this._target);
  49604. };
  49605. StopAnimationAction.prototype.serialize = function (parent) {
  49606. return _super.prototype._serialize.call(this, {
  49607. name: "StopAnimationAction",
  49608. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  49609. }, parent);
  49610. };
  49611. return StopAnimationAction;
  49612. }(BABYLON.Action));
  49613. BABYLON.StopAnimationAction = StopAnimationAction;
  49614. var DoNothingAction = /** @class */ (function (_super) {
  49615. __extends(DoNothingAction, _super);
  49616. function DoNothingAction(triggerOptions, condition) {
  49617. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  49618. return _super.call(this, triggerOptions, condition) || this;
  49619. }
  49620. DoNothingAction.prototype.execute = function () {
  49621. };
  49622. DoNothingAction.prototype.serialize = function (parent) {
  49623. return _super.prototype._serialize.call(this, {
  49624. name: "DoNothingAction",
  49625. properties: []
  49626. }, parent);
  49627. };
  49628. return DoNothingAction;
  49629. }(BABYLON.Action));
  49630. BABYLON.DoNothingAction = DoNothingAction;
  49631. var CombineAction = /** @class */ (function (_super) {
  49632. __extends(CombineAction, _super);
  49633. function CombineAction(triggerOptions, children, condition) {
  49634. var _this = _super.call(this, triggerOptions, condition) || this;
  49635. _this.children = children;
  49636. return _this;
  49637. }
  49638. CombineAction.prototype._prepare = function () {
  49639. for (var index = 0; index < this.children.length; index++) {
  49640. this.children[index]._actionManager = this._actionManager;
  49641. this.children[index]._prepare();
  49642. }
  49643. };
  49644. CombineAction.prototype.execute = function (evt) {
  49645. for (var index = 0; index < this.children.length; index++) {
  49646. this.children[index].execute(evt);
  49647. }
  49648. };
  49649. CombineAction.prototype.serialize = function (parent) {
  49650. var serializationObject = _super.prototype._serialize.call(this, {
  49651. name: "CombineAction",
  49652. properties: [],
  49653. combine: []
  49654. }, parent);
  49655. for (var i = 0; i < this.children.length; i++) {
  49656. serializationObject.combine.push(this.children[i].serialize(null));
  49657. }
  49658. return serializationObject;
  49659. };
  49660. return CombineAction;
  49661. }(BABYLON.Action));
  49662. BABYLON.CombineAction = CombineAction;
  49663. var ExecuteCodeAction = /** @class */ (function (_super) {
  49664. __extends(ExecuteCodeAction, _super);
  49665. function ExecuteCodeAction(triggerOptions, func, condition) {
  49666. var _this = _super.call(this, triggerOptions, condition) || this;
  49667. _this.func = func;
  49668. return _this;
  49669. }
  49670. ExecuteCodeAction.prototype.execute = function (evt) {
  49671. this.func(evt);
  49672. };
  49673. return ExecuteCodeAction;
  49674. }(BABYLON.Action));
  49675. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  49676. var SetParentAction = /** @class */ (function (_super) {
  49677. __extends(SetParentAction, _super);
  49678. function SetParentAction(triggerOptions, target, parent, condition) {
  49679. var _this = _super.call(this, triggerOptions, condition) || this;
  49680. _this._target = target;
  49681. _this._parent = parent;
  49682. return _this;
  49683. }
  49684. SetParentAction.prototype._prepare = function () {
  49685. };
  49686. SetParentAction.prototype.execute = function () {
  49687. if (this._target.parent === this._parent) {
  49688. return;
  49689. }
  49690. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  49691. invertParentWorldMatrix.invert();
  49692. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  49693. this._target.parent = this._parent;
  49694. };
  49695. SetParentAction.prototype.serialize = function (parent) {
  49696. return _super.prototype._serialize.call(this, {
  49697. name: "SetParentAction",
  49698. properties: [
  49699. BABYLON.Action._GetTargetProperty(this._target),
  49700. BABYLON.Action._GetTargetProperty(this._parent),
  49701. ]
  49702. }, parent);
  49703. };
  49704. return SetParentAction;
  49705. }(BABYLON.Action));
  49706. BABYLON.SetParentAction = SetParentAction;
  49707. var PlaySoundAction = /** @class */ (function (_super) {
  49708. __extends(PlaySoundAction, _super);
  49709. function PlaySoundAction(triggerOptions, sound, condition) {
  49710. var _this = _super.call(this, triggerOptions, condition) || this;
  49711. _this._sound = sound;
  49712. return _this;
  49713. }
  49714. PlaySoundAction.prototype._prepare = function () {
  49715. };
  49716. PlaySoundAction.prototype.execute = function () {
  49717. if (this._sound !== undefined)
  49718. this._sound.play();
  49719. };
  49720. PlaySoundAction.prototype.serialize = function (parent) {
  49721. return _super.prototype._serialize.call(this, {
  49722. name: "PlaySoundAction",
  49723. properties: [{ name: "sound", value: this._sound.name }]
  49724. }, parent);
  49725. };
  49726. return PlaySoundAction;
  49727. }(BABYLON.Action));
  49728. BABYLON.PlaySoundAction = PlaySoundAction;
  49729. var StopSoundAction = /** @class */ (function (_super) {
  49730. __extends(StopSoundAction, _super);
  49731. function StopSoundAction(triggerOptions, sound, condition) {
  49732. var _this = _super.call(this, triggerOptions, condition) || this;
  49733. _this._sound = sound;
  49734. return _this;
  49735. }
  49736. StopSoundAction.prototype._prepare = function () {
  49737. };
  49738. StopSoundAction.prototype.execute = function () {
  49739. if (this._sound !== undefined)
  49740. this._sound.stop();
  49741. };
  49742. StopSoundAction.prototype.serialize = function (parent) {
  49743. return _super.prototype._serialize.call(this, {
  49744. name: "StopSoundAction",
  49745. properties: [{ name: "sound", value: this._sound.name }]
  49746. }, parent);
  49747. };
  49748. return StopSoundAction;
  49749. }(BABYLON.Action));
  49750. BABYLON.StopSoundAction = StopSoundAction;
  49751. })(BABYLON || (BABYLON = {}));
  49752. //# sourceMappingURL=babylon.directActions.js.map
  49753. var BABYLON;
  49754. (function (BABYLON) {
  49755. var SpriteManager = /** @class */ (function () {
  49756. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  49757. if (epsilon === void 0) { epsilon = 0.01; }
  49758. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49759. this.name = name;
  49760. this.sprites = new Array();
  49761. this.renderingGroupId = 0;
  49762. this.layerMask = 0x0FFFFFFF;
  49763. this.fogEnabled = true;
  49764. this.isPickable = false;
  49765. /**
  49766. * An event triggered when the manager is disposed.
  49767. * @type {BABYLON.Observable}
  49768. */
  49769. this.onDisposeObservable = new BABYLON.Observable();
  49770. this._vertexBuffers = {};
  49771. this._capacity = capacity;
  49772. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  49773. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49774. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49775. if (cellSize.width && cellSize.height) {
  49776. this.cellWidth = cellSize.width;
  49777. this.cellHeight = cellSize.height;
  49778. }
  49779. else if (cellSize !== undefined) {
  49780. this.cellWidth = cellSize;
  49781. this.cellHeight = cellSize;
  49782. }
  49783. else {
  49784. return;
  49785. }
  49786. this._epsilon = epsilon;
  49787. this._scene = scene;
  49788. this._scene.spriteManagers.push(this);
  49789. var indices = [];
  49790. var index = 0;
  49791. for (var count = 0; count < capacity; count++) {
  49792. indices.push(index);
  49793. indices.push(index + 1);
  49794. indices.push(index + 2);
  49795. indices.push(index);
  49796. indices.push(index + 2);
  49797. indices.push(index + 3);
  49798. index += 4;
  49799. }
  49800. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  49801. // VBO
  49802. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  49803. this._vertexData = new Float32Array(capacity * 16 * 4);
  49804. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  49805. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  49806. var options = this._buffer.createVertexBuffer("options", 4, 4);
  49807. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  49808. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  49809. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  49810. this._vertexBuffers["options"] = options;
  49811. this._vertexBuffers["cellInfo"] = cellInfo;
  49812. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  49813. // Effects
  49814. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  49815. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  49816. }
  49817. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  49818. set: function (callback) {
  49819. if (this._onDisposeObserver) {
  49820. this.onDisposeObservable.remove(this._onDisposeObserver);
  49821. }
  49822. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  49823. },
  49824. enumerable: true,
  49825. configurable: true
  49826. });
  49827. Object.defineProperty(SpriteManager.prototype, "texture", {
  49828. get: function () {
  49829. return this._spriteTexture;
  49830. },
  49831. set: function (value) {
  49832. this._spriteTexture = value;
  49833. },
  49834. enumerable: true,
  49835. configurable: true
  49836. });
  49837. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  49838. var arrayOffset = index * 16;
  49839. if (offsetX === 0)
  49840. offsetX = this._epsilon;
  49841. else if (offsetX === 1)
  49842. offsetX = 1 - this._epsilon;
  49843. if (offsetY === 0)
  49844. offsetY = this._epsilon;
  49845. else if (offsetY === 1)
  49846. offsetY = 1 - this._epsilon;
  49847. this._vertexData[arrayOffset] = sprite.position.x;
  49848. this._vertexData[arrayOffset + 1] = sprite.position.y;
  49849. this._vertexData[arrayOffset + 2] = sprite.position.z;
  49850. this._vertexData[arrayOffset + 3] = sprite.angle;
  49851. this._vertexData[arrayOffset + 4] = sprite.width;
  49852. this._vertexData[arrayOffset + 5] = sprite.height;
  49853. this._vertexData[arrayOffset + 6] = offsetX;
  49854. this._vertexData[arrayOffset + 7] = offsetY;
  49855. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  49856. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  49857. var offset = (sprite.cellIndex / rowSize) >> 0;
  49858. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  49859. this._vertexData[arrayOffset + 11] = offset;
  49860. // Color
  49861. this._vertexData[arrayOffset + 12] = sprite.color.r;
  49862. this._vertexData[arrayOffset + 13] = sprite.color.g;
  49863. this._vertexData[arrayOffset + 14] = sprite.color.b;
  49864. this._vertexData[arrayOffset + 15] = sprite.color.a;
  49865. };
  49866. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  49867. var count = Math.min(this._capacity, this.sprites.length);
  49868. var min = BABYLON.Vector3.Zero();
  49869. var max = BABYLON.Vector3.Zero();
  49870. var distance = Number.MAX_VALUE;
  49871. var currentSprite = null;
  49872. var cameraSpacePosition = BABYLON.Vector3.Zero();
  49873. var cameraView = camera.getViewMatrix();
  49874. for (var index = 0; index < count; index++) {
  49875. var sprite = this.sprites[index];
  49876. if (!sprite) {
  49877. continue;
  49878. }
  49879. if (predicate) {
  49880. if (!predicate(sprite)) {
  49881. continue;
  49882. }
  49883. }
  49884. else if (!sprite.isPickable) {
  49885. continue;
  49886. }
  49887. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  49888. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  49889. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  49890. if (ray.intersectsBoxMinMax(min, max)) {
  49891. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  49892. if (distance > currentDistance) {
  49893. distance = currentDistance;
  49894. currentSprite = sprite;
  49895. if (fastCheck) {
  49896. break;
  49897. }
  49898. }
  49899. }
  49900. }
  49901. if (currentSprite) {
  49902. var result = new BABYLON.PickingInfo();
  49903. result.hit = true;
  49904. result.pickedSprite = currentSprite;
  49905. result.distance = distance;
  49906. return result;
  49907. }
  49908. return null;
  49909. };
  49910. SpriteManager.prototype.render = function () {
  49911. // Check
  49912. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  49913. return;
  49914. var engine = this._scene.getEngine();
  49915. var baseSize = this._spriteTexture.getBaseSize();
  49916. // Sprites
  49917. var deltaTime = engine.getDeltaTime();
  49918. var max = Math.min(this._capacity, this.sprites.length);
  49919. var rowSize = baseSize.width / this.cellWidth;
  49920. var offset = 0;
  49921. for (var index = 0; index < max; index++) {
  49922. var sprite = this.sprites[index];
  49923. if (!sprite) {
  49924. continue;
  49925. }
  49926. sprite._animate(deltaTime);
  49927. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  49928. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  49929. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  49930. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  49931. }
  49932. this._buffer.update(this._vertexData);
  49933. // Render
  49934. var effect = this._effectBase;
  49935. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49936. effect = this._effectFog;
  49937. }
  49938. engine.enableEffect(effect);
  49939. var viewMatrix = this._scene.getViewMatrix();
  49940. effect.setTexture("diffuseSampler", this._spriteTexture);
  49941. effect.setMatrix("view", viewMatrix);
  49942. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  49943. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  49944. // Fog
  49945. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  49946. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  49947. effect.setColor3("vFogColor", this._scene.fogColor);
  49948. }
  49949. // VBOs
  49950. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  49951. // Draw order
  49952. engine.setDepthFunctionToLessOrEqual();
  49953. effect.setBool("alphaTest", true);
  49954. engine.setColorWrite(false);
  49955. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49956. engine.setColorWrite(true);
  49957. effect.setBool("alphaTest", false);
  49958. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  49959. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  49960. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  49961. };
  49962. SpriteManager.prototype.dispose = function () {
  49963. if (this._buffer) {
  49964. this._buffer.dispose();
  49965. this._buffer = null;
  49966. }
  49967. if (this._indexBuffer) {
  49968. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  49969. this._indexBuffer = null;
  49970. }
  49971. if (this._spriteTexture) {
  49972. this._spriteTexture.dispose();
  49973. this._spriteTexture = null;
  49974. }
  49975. // Remove from scene
  49976. var index = this._scene.spriteManagers.indexOf(this);
  49977. this._scene.spriteManagers.splice(index, 1);
  49978. // Callback
  49979. this.onDisposeObservable.notifyObservers(this);
  49980. this.onDisposeObservable.clear();
  49981. };
  49982. return SpriteManager;
  49983. }());
  49984. BABYLON.SpriteManager = SpriteManager;
  49985. })(BABYLON || (BABYLON = {}));
  49986. //# sourceMappingURL=babylon.spriteManager.js.map
  49987. var BABYLON;
  49988. (function (BABYLON) {
  49989. var Sprite = /** @class */ (function () {
  49990. function Sprite(name, manager) {
  49991. this.name = name;
  49992. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  49993. this.width = 1.0;
  49994. this.height = 1.0;
  49995. this.angle = 0;
  49996. this.cellIndex = 0;
  49997. this.invertU = 0;
  49998. this.invertV = 0;
  49999. this.animations = new Array();
  50000. this.isPickable = false;
  50001. this._animationStarted = false;
  50002. this._loopAnimation = false;
  50003. this._fromIndex = 0;
  50004. this._toIndex = 0;
  50005. this._delay = 0;
  50006. this._direction = 1;
  50007. this._time = 0;
  50008. this._manager = manager;
  50009. this._manager.sprites.push(this);
  50010. this.position = BABYLON.Vector3.Zero();
  50011. }
  50012. Object.defineProperty(Sprite.prototype, "size", {
  50013. get: function () {
  50014. return this.width;
  50015. },
  50016. set: function (value) {
  50017. this.width = value;
  50018. this.height = value;
  50019. },
  50020. enumerable: true,
  50021. configurable: true
  50022. });
  50023. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  50024. this._fromIndex = from;
  50025. this._toIndex = to;
  50026. this._loopAnimation = loop;
  50027. this._delay = delay;
  50028. this._animationStarted = true;
  50029. this._direction = from < to ? 1 : -1;
  50030. this.cellIndex = from;
  50031. this._time = 0;
  50032. this._onAnimationEnd = onAnimationEnd;
  50033. };
  50034. Sprite.prototype.stopAnimation = function () {
  50035. this._animationStarted = false;
  50036. };
  50037. Sprite.prototype._animate = function (deltaTime) {
  50038. if (!this._animationStarted)
  50039. return;
  50040. this._time += deltaTime;
  50041. if (this._time > this._delay) {
  50042. this._time = this._time % this._delay;
  50043. this.cellIndex += this._direction;
  50044. if (this.cellIndex > this._toIndex) {
  50045. if (this._loopAnimation) {
  50046. this.cellIndex = this._fromIndex;
  50047. }
  50048. else {
  50049. this.cellIndex = this._toIndex;
  50050. this._animationStarted = false;
  50051. if (this._onAnimationEnd) {
  50052. this._onAnimationEnd();
  50053. }
  50054. if (this.disposeWhenFinishedAnimating) {
  50055. this.dispose();
  50056. }
  50057. }
  50058. }
  50059. }
  50060. };
  50061. Sprite.prototype.dispose = function () {
  50062. for (var i = 0; i < this._manager.sprites.length; i++) {
  50063. if (this._manager.sprites[i] == this) {
  50064. this._manager.sprites.splice(i, 1);
  50065. }
  50066. }
  50067. };
  50068. return Sprite;
  50069. }());
  50070. BABYLON.Sprite = Sprite;
  50071. })(BABYLON || (BABYLON = {}));
  50072. //# sourceMappingURL=babylon.sprite.js.map
  50073. var BABYLON;
  50074. (function (BABYLON) {
  50075. var IntersectionInfo = /** @class */ (function () {
  50076. function IntersectionInfo(bu, bv, distance) {
  50077. this.bu = bu;
  50078. this.bv = bv;
  50079. this.distance = distance;
  50080. this.faceId = 0;
  50081. this.subMeshId = 0;
  50082. }
  50083. return IntersectionInfo;
  50084. }());
  50085. BABYLON.IntersectionInfo = IntersectionInfo;
  50086. var PickingInfo = /** @class */ (function () {
  50087. function PickingInfo() {
  50088. this.hit = false;
  50089. this.distance = 0;
  50090. this.pickedPoint = null;
  50091. this.pickedMesh = null;
  50092. this.bu = 0;
  50093. this.bv = 0;
  50094. this.faceId = -1;
  50095. this.subMeshId = 0;
  50096. this.pickedSprite = null;
  50097. }
  50098. // Methods
  50099. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  50100. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  50101. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  50102. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  50103. return null;
  50104. }
  50105. var indices = this.pickedMesh.getIndices();
  50106. if (!indices) {
  50107. return null;
  50108. }
  50109. var result;
  50110. if (useVerticesNormals) {
  50111. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50112. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  50113. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  50114. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  50115. normal0 = normal0.scale(this.bu);
  50116. normal1 = normal1.scale(this.bv);
  50117. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  50118. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  50119. }
  50120. else {
  50121. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50122. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  50123. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  50124. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  50125. var p1p2 = vertex1.subtract(vertex2);
  50126. var p3p2 = vertex3.subtract(vertex2);
  50127. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  50128. }
  50129. if (useWorldCoordinates) {
  50130. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  50131. }
  50132. return BABYLON.Vector3.Normalize(result);
  50133. };
  50134. PickingInfo.prototype.getTextureCoordinates = function () {
  50135. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  50136. return null;
  50137. }
  50138. var indices = this.pickedMesh.getIndices();
  50139. if (!indices) {
  50140. return null;
  50141. }
  50142. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50143. if (!uvs) {
  50144. return null;
  50145. }
  50146. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  50147. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  50148. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  50149. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  50150. uv1 = uv1.scale(this.bu);
  50151. uv2 = uv2.scale(this.bv);
  50152. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  50153. };
  50154. return PickingInfo;
  50155. }());
  50156. BABYLON.PickingInfo = PickingInfo;
  50157. })(BABYLON || (BABYLON = {}));
  50158. //# sourceMappingURL=babylon.pickingInfo.js.map
  50159. var BABYLON;
  50160. (function (BABYLON) {
  50161. var Ray = /** @class */ (function () {
  50162. function Ray(origin, direction, length) {
  50163. if (length === void 0) { length = Number.MAX_VALUE; }
  50164. this.origin = origin;
  50165. this.direction = direction;
  50166. this.length = length;
  50167. }
  50168. // Methods
  50169. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  50170. var d = 0.0;
  50171. var maxValue = Number.MAX_VALUE;
  50172. var inv;
  50173. var min;
  50174. var max;
  50175. var temp;
  50176. if (Math.abs(this.direction.x) < 0.0000001) {
  50177. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  50178. return false;
  50179. }
  50180. }
  50181. else {
  50182. inv = 1.0 / this.direction.x;
  50183. min = (minimum.x - this.origin.x) * inv;
  50184. max = (maximum.x - this.origin.x) * inv;
  50185. if (max === -Infinity) {
  50186. max = Infinity;
  50187. }
  50188. if (min > max) {
  50189. temp = min;
  50190. min = max;
  50191. max = temp;
  50192. }
  50193. d = Math.max(min, d);
  50194. maxValue = Math.min(max, maxValue);
  50195. if (d > maxValue) {
  50196. return false;
  50197. }
  50198. }
  50199. if (Math.abs(this.direction.y) < 0.0000001) {
  50200. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  50201. return false;
  50202. }
  50203. }
  50204. else {
  50205. inv = 1.0 / this.direction.y;
  50206. min = (minimum.y - this.origin.y) * inv;
  50207. max = (maximum.y - this.origin.y) * inv;
  50208. if (max === -Infinity) {
  50209. max = Infinity;
  50210. }
  50211. if (min > max) {
  50212. temp = min;
  50213. min = max;
  50214. max = temp;
  50215. }
  50216. d = Math.max(min, d);
  50217. maxValue = Math.min(max, maxValue);
  50218. if (d > maxValue) {
  50219. return false;
  50220. }
  50221. }
  50222. if (Math.abs(this.direction.z) < 0.0000001) {
  50223. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  50224. return false;
  50225. }
  50226. }
  50227. else {
  50228. inv = 1.0 / this.direction.z;
  50229. min = (minimum.z - this.origin.z) * inv;
  50230. max = (maximum.z - this.origin.z) * inv;
  50231. if (max === -Infinity) {
  50232. max = Infinity;
  50233. }
  50234. if (min > max) {
  50235. temp = min;
  50236. min = max;
  50237. max = temp;
  50238. }
  50239. d = Math.max(min, d);
  50240. maxValue = Math.min(max, maxValue);
  50241. if (d > maxValue) {
  50242. return false;
  50243. }
  50244. }
  50245. return true;
  50246. };
  50247. Ray.prototype.intersectsBox = function (box) {
  50248. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  50249. };
  50250. Ray.prototype.intersectsSphere = function (sphere) {
  50251. var x = sphere.center.x - this.origin.x;
  50252. var y = sphere.center.y - this.origin.y;
  50253. var z = sphere.center.z - this.origin.z;
  50254. var pyth = (x * x) + (y * y) + (z * z);
  50255. var rr = sphere.radius * sphere.radius;
  50256. if (pyth <= rr) {
  50257. return true;
  50258. }
  50259. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  50260. if (dot < 0.0) {
  50261. return false;
  50262. }
  50263. var temp = pyth - (dot * dot);
  50264. return temp <= rr;
  50265. };
  50266. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  50267. if (!this._edge1) {
  50268. this._edge1 = BABYLON.Vector3.Zero();
  50269. this._edge2 = BABYLON.Vector3.Zero();
  50270. this._pvec = BABYLON.Vector3.Zero();
  50271. this._tvec = BABYLON.Vector3.Zero();
  50272. this._qvec = BABYLON.Vector3.Zero();
  50273. }
  50274. vertex1.subtractToRef(vertex0, this._edge1);
  50275. vertex2.subtractToRef(vertex0, this._edge2);
  50276. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  50277. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  50278. if (det === 0) {
  50279. return null;
  50280. }
  50281. var invdet = 1 / det;
  50282. this.origin.subtractToRef(vertex0, this._tvec);
  50283. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  50284. if (bu < 0 || bu > 1.0) {
  50285. return null;
  50286. }
  50287. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  50288. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  50289. if (bv < 0 || bu + bv > 1.0) {
  50290. return null;
  50291. }
  50292. //check if the distance is longer than the predefined length.
  50293. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  50294. if (distance > this.length) {
  50295. return null;
  50296. }
  50297. return new BABYLON.IntersectionInfo(bu, bv, distance);
  50298. };
  50299. Ray.prototype.intersectsPlane = function (plane) {
  50300. var distance;
  50301. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  50302. if (Math.abs(result1) < 9.99999997475243E-07) {
  50303. return null;
  50304. }
  50305. else {
  50306. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  50307. distance = (-plane.d - result2) / result1;
  50308. if (distance < 0.0) {
  50309. if (distance < -9.99999997475243E-07) {
  50310. return null;
  50311. }
  50312. else {
  50313. return 0;
  50314. }
  50315. }
  50316. return distance;
  50317. }
  50318. };
  50319. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  50320. var tm = BABYLON.Tmp.Matrix[0];
  50321. mesh.getWorldMatrix().invertToRef(tm);
  50322. if (this._tmpRay) {
  50323. Ray.TransformToRef(this, tm, this._tmpRay);
  50324. }
  50325. else {
  50326. this._tmpRay = Ray.Transform(this, tm);
  50327. }
  50328. return mesh.intersects(this._tmpRay, fastCheck);
  50329. };
  50330. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  50331. if (results) {
  50332. results.length = 0;
  50333. }
  50334. else {
  50335. results = [];
  50336. }
  50337. for (var i = 0; i < meshes.length; i++) {
  50338. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  50339. if (pickInfo.hit) {
  50340. results.push(pickInfo);
  50341. }
  50342. }
  50343. results.sort(this._comparePickingInfo);
  50344. return results;
  50345. };
  50346. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  50347. if (pickingInfoA.distance < pickingInfoB.distance) {
  50348. return -1;
  50349. }
  50350. else if (pickingInfoA.distance > pickingInfoB.distance) {
  50351. return 1;
  50352. }
  50353. else {
  50354. return 0;
  50355. }
  50356. };
  50357. /**
  50358. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  50359. * @param sega the first point of the segment to test the intersection against
  50360. * @param segb the second point of the segment to test the intersection against
  50361. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  50362. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  50363. */
  50364. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  50365. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  50366. var u = segb.subtract(sega);
  50367. var v = rsegb.subtract(this.origin);
  50368. var w = sega.subtract(this.origin);
  50369. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  50370. var b = BABYLON.Vector3.Dot(u, v);
  50371. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  50372. var d = BABYLON.Vector3.Dot(u, w);
  50373. var e = BABYLON.Vector3.Dot(v, w);
  50374. var D = a * c - b * b; // always >= 0
  50375. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  50376. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  50377. // compute the line parameters of the two closest points
  50378. if (D < Ray.smallnum) {
  50379. sN = 0.0; // force using point P0 on segment S1
  50380. sD = 1.0; // to prevent possible division by 0.0 later
  50381. tN = e;
  50382. tD = c;
  50383. }
  50384. else {
  50385. sN = (b * e - c * d);
  50386. tN = (a * e - b * d);
  50387. if (sN < 0.0) {
  50388. sN = 0.0;
  50389. tN = e;
  50390. tD = c;
  50391. }
  50392. else if (sN > sD) {
  50393. sN = sD;
  50394. tN = e + b;
  50395. tD = c;
  50396. }
  50397. }
  50398. if (tN < 0.0) {
  50399. tN = 0.0;
  50400. // recompute sc for this edge
  50401. if (-d < 0.0) {
  50402. sN = 0.0;
  50403. }
  50404. else if (-d > a)
  50405. sN = sD;
  50406. else {
  50407. sN = -d;
  50408. sD = a;
  50409. }
  50410. }
  50411. else if (tN > tD) {
  50412. tN = tD;
  50413. // recompute sc for this edge
  50414. if ((-d + b) < 0.0) {
  50415. sN = 0;
  50416. }
  50417. else if ((-d + b) > a) {
  50418. sN = sD;
  50419. }
  50420. else {
  50421. sN = (-d + b);
  50422. sD = a;
  50423. }
  50424. }
  50425. // finally do the division to get sc and tc
  50426. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  50427. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  50428. // get the difference of the two closest points
  50429. var qtc = v.multiplyByFloats(tc, tc, tc);
  50430. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  50431. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  50432. if (isIntersected) {
  50433. return qtc.length();
  50434. }
  50435. return -1;
  50436. };
  50437. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50438. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  50439. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  50440. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  50441. this.direction.normalize();
  50442. return this;
  50443. };
  50444. // Statics
  50445. Ray.Zero = function () {
  50446. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  50447. };
  50448. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50449. var result = Ray.Zero();
  50450. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  50451. };
  50452. /**
  50453. * 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
  50454. * transformed to the given world matrix.
  50455. * @param origin The origin point
  50456. * @param end The end point
  50457. * @param world a matrix to transform the ray to. Default is the identity matrix.
  50458. */
  50459. Ray.CreateNewFromTo = function (origin, end, world) {
  50460. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  50461. var direction = end.subtract(origin);
  50462. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  50463. direction.normalize();
  50464. return Ray.Transform(new Ray(origin, direction, length), world);
  50465. };
  50466. Ray.Transform = function (ray, matrix) {
  50467. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  50468. Ray.TransformToRef(ray, matrix, result);
  50469. return result;
  50470. };
  50471. Ray.TransformToRef = function (ray, matrix, result) {
  50472. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  50473. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  50474. result.length = ray.length;
  50475. var dir = result.direction;
  50476. var len = dir.length();
  50477. if (!(len === 0 || len === 1)) {
  50478. var num = 1.0 / len;
  50479. dir.x *= num;
  50480. dir.y *= num;
  50481. dir.z *= num;
  50482. result.length *= len;
  50483. }
  50484. };
  50485. Ray.smallnum = 0.00000001;
  50486. Ray.rayl = 10e8;
  50487. return Ray;
  50488. }());
  50489. BABYLON.Ray = Ray;
  50490. })(BABYLON || (BABYLON = {}));
  50491. //# sourceMappingURL=babylon.ray.js.map
  50492. var BABYLON;
  50493. (function (BABYLON) {
  50494. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  50495. if (boxMin.x > sphereCenter.x + sphereRadius)
  50496. return false;
  50497. if (sphereCenter.x - sphereRadius > boxMax.x)
  50498. return false;
  50499. if (boxMin.y > sphereCenter.y + sphereRadius)
  50500. return false;
  50501. if (sphereCenter.y - sphereRadius > boxMax.y)
  50502. return false;
  50503. if (boxMin.z > sphereCenter.z + sphereRadius)
  50504. return false;
  50505. if (sphereCenter.z - sphereRadius > boxMax.z)
  50506. return false;
  50507. return true;
  50508. };
  50509. var getLowestRoot = (function () {
  50510. var result = { root: 0, found: false };
  50511. return function (a, b, c, maxR) {
  50512. result.root = 0;
  50513. result.found = false;
  50514. var determinant = b * b - 4.0 * a * c;
  50515. if (determinant < 0)
  50516. return result;
  50517. var sqrtD = Math.sqrt(determinant);
  50518. var r1 = (-b - sqrtD) / (2.0 * a);
  50519. var r2 = (-b + sqrtD) / (2.0 * a);
  50520. if (r1 > r2) {
  50521. var temp = r2;
  50522. r2 = r1;
  50523. r1 = temp;
  50524. }
  50525. if (r1 > 0 && r1 < maxR) {
  50526. result.root = r1;
  50527. result.found = true;
  50528. return result;
  50529. }
  50530. if (r2 > 0 && r2 < maxR) {
  50531. result.root = r2;
  50532. result.found = true;
  50533. return result;
  50534. }
  50535. return result;
  50536. };
  50537. })();
  50538. var Collider = /** @class */ (function () {
  50539. function Collider() {
  50540. this._collisionPoint = BABYLON.Vector3.Zero();
  50541. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  50542. this._tempVector = BABYLON.Vector3.Zero();
  50543. this._tempVector2 = BABYLON.Vector3.Zero();
  50544. this._tempVector3 = BABYLON.Vector3.Zero();
  50545. this._tempVector4 = BABYLON.Vector3.Zero();
  50546. this._edge = BABYLON.Vector3.Zero();
  50547. this._baseToVertex = BABYLON.Vector3.Zero();
  50548. this._destinationPoint = BABYLON.Vector3.Zero();
  50549. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  50550. this._displacementVector = BABYLON.Vector3.Zero();
  50551. this._radius = BABYLON.Vector3.One();
  50552. this._retry = 0;
  50553. this._basePointWorld = BABYLON.Vector3.Zero();
  50554. this._velocityWorld = BABYLON.Vector3.Zero();
  50555. this._normalizedVelocity = BABYLON.Vector3.Zero();
  50556. this._collisionMask = -1;
  50557. }
  50558. Object.defineProperty(Collider.prototype, "collisionMask", {
  50559. get: function () {
  50560. return this._collisionMask;
  50561. },
  50562. set: function (mask) {
  50563. this._collisionMask = !isNaN(mask) ? mask : -1;
  50564. },
  50565. enumerable: true,
  50566. configurable: true
  50567. });
  50568. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  50569. /**
  50570. * Gets the plane normal used to compute the sliding response (in local space)
  50571. */
  50572. get: function () {
  50573. return this._slidePlaneNormal;
  50574. },
  50575. enumerable: true,
  50576. configurable: true
  50577. });
  50578. // Methods
  50579. Collider.prototype._initialize = function (source, dir, e) {
  50580. this._velocity = dir;
  50581. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  50582. this._basePoint = source;
  50583. source.multiplyToRef(this._radius, this._basePointWorld);
  50584. dir.multiplyToRef(this._radius, this._velocityWorld);
  50585. this._velocityWorldLength = this._velocityWorld.length();
  50586. this._epsilon = e;
  50587. this.collisionFound = false;
  50588. };
  50589. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  50590. pa.subtractToRef(point, this._tempVector);
  50591. pb.subtractToRef(point, this._tempVector2);
  50592. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  50593. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50594. if (d < 0)
  50595. return false;
  50596. pc.subtractToRef(point, this._tempVector3);
  50597. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  50598. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50599. if (d < 0)
  50600. return false;
  50601. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  50602. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50603. return d >= 0;
  50604. };
  50605. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  50606. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  50607. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  50608. if (distance > this._velocityWorldLength + max + sphereRadius) {
  50609. return false;
  50610. }
  50611. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  50612. return false;
  50613. return true;
  50614. };
  50615. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  50616. var t0;
  50617. var embeddedInPlane = false;
  50618. //defensive programming, actually not needed.
  50619. if (!trianglePlaneArray) {
  50620. trianglePlaneArray = [];
  50621. }
  50622. if (!trianglePlaneArray[faceIndex]) {
  50623. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  50624. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  50625. }
  50626. var trianglePlane = trianglePlaneArray[faceIndex];
  50627. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  50628. return;
  50629. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  50630. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  50631. if (normalDotVelocity == 0) {
  50632. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  50633. return;
  50634. embeddedInPlane = true;
  50635. t0 = 0;
  50636. }
  50637. else {
  50638. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50639. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50640. if (t0 > t1) {
  50641. var temp = t1;
  50642. t1 = t0;
  50643. t0 = temp;
  50644. }
  50645. if (t0 > 1.0 || t1 < 0.0)
  50646. return;
  50647. if (t0 < 0)
  50648. t0 = 0;
  50649. if (t0 > 1.0)
  50650. t0 = 1.0;
  50651. }
  50652. this._collisionPoint.copyFromFloats(0, 0, 0);
  50653. var found = false;
  50654. var t = 1.0;
  50655. if (!embeddedInPlane) {
  50656. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  50657. this._velocity.scaleToRef(t0, this._tempVector);
  50658. this._planeIntersectionPoint.addInPlace(this._tempVector);
  50659. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  50660. found = true;
  50661. t = t0;
  50662. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  50663. }
  50664. }
  50665. if (!found) {
  50666. var velocitySquaredLength = this._velocity.lengthSquared();
  50667. var a = velocitySquaredLength;
  50668. this._basePoint.subtractToRef(p1, this._tempVector);
  50669. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50670. var c = this._tempVector.lengthSquared() - 1.0;
  50671. var lowestRoot = getLowestRoot(a, b, c, t);
  50672. if (lowestRoot.found) {
  50673. t = lowestRoot.root;
  50674. found = true;
  50675. this._collisionPoint.copyFrom(p1);
  50676. }
  50677. this._basePoint.subtractToRef(p2, this._tempVector);
  50678. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50679. c = this._tempVector.lengthSquared() - 1.0;
  50680. lowestRoot = getLowestRoot(a, b, c, t);
  50681. if (lowestRoot.found) {
  50682. t = lowestRoot.root;
  50683. found = true;
  50684. this._collisionPoint.copyFrom(p2);
  50685. }
  50686. this._basePoint.subtractToRef(p3, this._tempVector);
  50687. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50688. c = this._tempVector.lengthSquared() - 1.0;
  50689. lowestRoot = getLowestRoot(a, b, c, t);
  50690. if (lowestRoot.found) {
  50691. t = lowestRoot.root;
  50692. found = true;
  50693. this._collisionPoint.copyFrom(p3);
  50694. }
  50695. p2.subtractToRef(p1, this._edge);
  50696. p1.subtractToRef(this._basePoint, this._baseToVertex);
  50697. var edgeSquaredLength = this._edge.lengthSquared();
  50698. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50699. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50700. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50701. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50702. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50703. lowestRoot = getLowestRoot(a, b, c, t);
  50704. if (lowestRoot.found) {
  50705. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50706. if (f >= 0.0 && f <= 1.0) {
  50707. t = lowestRoot.root;
  50708. found = true;
  50709. this._edge.scaleInPlace(f);
  50710. p1.addToRef(this._edge, this._collisionPoint);
  50711. }
  50712. }
  50713. p3.subtractToRef(p2, this._edge);
  50714. p2.subtractToRef(this._basePoint, this._baseToVertex);
  50715. edgeSquaredLength = this._edge.lengthSquared();
  50716. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50717. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50718. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50719. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50720. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50721. lowestRoot = getLowestRoot(a, b, c, t);
  50722. if (lowestRoot.found) {
  50723. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50724. if (f >= 0.0 && f <= 1.0) {
  50725. t = lowestRoot.root;
  50726. found = true;
  50727. this._edge.scaleInPlace(f);
  50728. p2.addToRef(this._edge, this._collisionPoint);
  50729. }
  50730. }
  50731. p1.subtractToRef(p3, this._edge);
  50732. p3.subtractToRef(this._basePoint, this._baseToVertex);
  50733. edgeSquaredLength = this._edge.lengthSquared();
  50734. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50735. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50736. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50737. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50738. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50739. lowestRoot = getLowestRoot(a, b, c, t);
  50740. if (lowestRoot.found) {
  50741. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50742. if (f >= 0.0 && f <= 1.0) {
  50743. t = lowestRoot.root;
  50744. found = true;
  50745. this._edge.scaleInPlace(f);
  50746. p3.addToRef(this._edge, this._collisionPoint);
  50747. }
  50748. }
  50749. }
  50750. if (found) {
  50751. var distToCollision = t * this._velocity.length();
  50752. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  50753. if (!this.intersectionPoint) {
  50754. this.intersectionPoint = this._collisionPoint.clone();
  50755. }
  50756. else {
  50757. this.intersectionPoint.copyFrom(this._collisionPoint);
  50758. }
  50759. this._nearestDistance = distToCollision;
  50760. this.collisionFound = true;
  50761. }
  50762. }
  50763. };
  50764. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  50765. for (var i = indexStart; i < indexEnd; i += 3) {
  50766. var p1 = pts[indices[i] - decal];
  50767. var p2 = pts[indices[i + 1] - decal];
  50768. var p3 = pts[indices[i + 2] - decal];
  50769. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  50770. }
  50771. };
  50772. Collider.prototype._getResponse = function (pos, vel) {
  50773. pos.addToRef(vel, this._destinationPoint);
  50774. vel.scaleInPlace((this._nearestDistance / vel.length()));
  50775. this._basePoint.addToRef(vel, pos);
  50776. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  50777. this._slidePlaneNormal.normalize();
  50778. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  50779. pos.addInPlace(this._displacementVector);
  50780. this.intersectionPoint.addInPlace(this._displacementVector);
  50781. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  50782. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  50783. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  50784. };
  50785. return Collider;
  50786. }());
  50787. BABYLON.Collider = Collider;
  50788. })(BABYLON || (BABYLON = {}));
  50789. //# sourceMappingURL=babylon.collider.js.map
  50790. var BABYLON;
  50791. (function (BABYLON) {
  50792. //WebWorker code will be inserted to this variable.
  50793. BABYLON.CollisionWorker = "";
  50794. var WorkerTaskType;
  50795. (function (WorkerTaskType) {
  50796. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  50797. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  50798. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  50799. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  50800. var WorkerReplyType;
  50801. (function (WorkerReplyType) {
  50802. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  50803. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  50804. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  50805. var CollisionCoordinatorWorker = /** @class */ (function () {
  50806. function CollisionCoordinatorWorker() {
  50807. var _this = this;
  50808. this._scaledPosition = BABYLON.Vector3.Zero();
  50809. this._scaledVelocity = BABYLON.Vector3.Zero();
  50810. this.onMeshUpdated = function (transformNode) {
  50811. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  50812. };
  50813. this.onGeometryUpdated = function (geometry) {
  50814. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  50815. };
  50816. this._afterRender = function () {
  50817. if (!_this._init)
  50818. return;
  50819. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  50820. return;
  50821. }
  50822. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  50823. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  50824. if (_this._runningUpdated > 4) {
  50825. return;
  50826. }
  50827. ++_this._runningUpdated;
  50828. var payload = {
  50829. updatedMeshes: _this._addUpdateMeshesList,
  50830. updatedGeometries: _this._addUpdateGeometriesList,
  50831. removedGeometries: _this._toRemoveGeometryArray,
  50832. removedMeshes: _this._toRemoveMeshesArray
  50833. };
  50834. var message = {
  50835. payload: payload,
  50836. taskType: WorkerTaskType.UPDATE
  50837. };
  50838. var serializable = [];
  50839. for (var id in payload.updatedGeometries) {
  50840. if (payload.updatedGeometries.hasOwnProperty(id)) {
  50841. //prepare transferables
  50842. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  50843. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  50844. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  50845. }
  50846. }
  50847. _this._worker.postMessage(message, serializable);
  50848. _this._addUpdateMeshesList = {};
  50849. _this._addUpdateGeometriesList = {};
  50850. _this._toRemoveGeometryArray = [];
  50851. _this._toRemoveMeshesArray = [];
  50852. };
  50853. this._onMessageFromWorker = function (e) {
  50854. var returnData = e.data;
  50855. if (returnData.error != WorkerReplyType.SUCCESS) {
  50856. //TODO what errors can be returned from the worker?
  50857. BABYLON.Tools.Warn("error returned from worker!");
  50858. return;
  50859. }
  50860. switch (returnData.taskType) {
  50861. case WorkerTaskType.INIT:
  50862. _this._init = true;
  50863. //Update the worked with ALL of the scene's current state
  50864. _this._scene.meshes.forEach(function (mesh) {
  50865. _this.onMeshAdded(mesh);
  50866. });
  50867. _this._scene.getGeometries().forEach(function (geometry) {
  50868. _this.onGeometryAdded(geometry);
  50869. });
  50870. break;
  50871. case WorkerTaskType.UPDATE:
  50872. _this._runningUpdated--;
  50873. break;
  50874. case WorkerTaskType.COLLIDE:
  50875. var returnPayload = returnData.payload;
  50876. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  50877. return;
  50878. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  50879. if (callback) {
  50880. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  50881. if (mesh) {
  50882. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  50883. }
  50884. }
  50885. //cleanup
  50886. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  50887. break;
  50888. }
  50889. };
  50890. this._collisionsCallbackArray = [];
  50891. this._init = false;
  50892. this._runningUpdated = 0;
  50893. this._addUpdateMeshesList = {};
  50894. this._addUpdateGeometriesList = {};
  50895. this._toRemoveGeometryArray = [];
  50896. this._toRemoveMeshesArray = [];
  50897. }
  50898. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50899. if (!this._init)
  50900. return;
  50901. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  50902. return;
  50903. position.divideToRef(collider._radius, this._scaledPosition);
  50904. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50905. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  50906. var payload = {
  50907. collider: {
  50908. position: this._scaledPosition.asArray(),
  50909. velocity: this._scaledVelocity.asArray(),
  50910. radius: collider._radius.asArray()
  50911. },
  50912. collisionId: collisionIndex,
  50913. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  50914. maximumRetry: maximumRetry
  50915. };
  50916. var message = {
  50917. payload: payload,
  50918. taskType: WorkerTaskType.COLLIDE
  50919. };
  50920. this._worker.postMessage(message);
  50921. };
  50922. CollisionCoordinatorWorker.prototype.init = function (scene) {
  50923. this._scene = scene;
  50924. this._scene.registerAfterRender(this._afterRender);
  50925. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  50926. this._worker = new Worker(workerUrl);
  50927. this._worker.onmessage = this._onMessageFromWorker;
  50928. var message = {
  50929. payload: {},
  50930. taskType: WorkerTaskType.INIT
  50931. };
  50932. this._worker.postMessage(message);
  50933. };
  50934. CollisionCoordinatorWorker.prototype.destroy = function () {
  50935. this._scene.unregisterAfterRender(this._afterRender);
  50936. this._worker.terminate();
  50937. };
  50938. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  50939. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  50940. this.onMeshUpdated(mesh);
  50941. };
  50942. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  50943. this._toRemoveMeshesArray.push(mesh.uniqueId);
  50944. };
  50945. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  50946. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  50947. geometry.onGeometryUpdated = this.onGeometryUpdated;
  50948. this.onGeometryUpdated(geometry);
  50949. };
  50950. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  50951. this._toRemoveGeometryArray.push(geometry.id);
  50952. };
  50953. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  50954. var submeshes = [];
  50955. if (mesh.subMeshes) {
  50956. submeshes = mesh.subMeshes.map(function (sm, idx) {
  50957. var boundingInfo = sm.getBoundingInfo();
  50958. return {
  50959. position: idx,
  50960. verticesStart: sm.verticesStart,
  50961. verticesCount: sm.verticesCount,
  50962. indexStart: sm.indexStart,
  50963. indexCount: sm.indexCount,
  50964. hasMaterial: !!sm.getMaterial(),
  50965. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50966. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50967. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50968. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  50969. };
  50970. });
  50971. }
  50972. var geometryId = null;
  50973. if (mesh instanceof BABYLON.Mesh) {
  50974. var geometry = mesh.geometry;
  50975. geometryId = geometry ? geometry.id : null;
  50976. }
  50977. else if (mesh instanceof BABYLON.InstancedMesh) {
  50978. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  50979. geometryId = geometry ? geometry.id : null;
  50980. }
  50981. var boundingInfo = mesh.getBoundingInfo();
  50982. return {
  50983. uniqueId: mesh.uniqueId,
  50984. id: mesh.id,
  50985. name: mesh.name,
  50986. geometryId: geometryId,
  50987. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  50988. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  50989. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  50990. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  50991. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  50992. subMeshes: submeshes,
  50993. checkCollisions: mesh.checkCollisions
  50994. };
  50995. };
  50996. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  50997. return {
  50998. id: geometry.id,
  50999. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  51000. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  51001. indices: new Uint32Array(geometry.getIndices() || []),
  51002. };
  51003. };
  51004. return CollisionCoordinatorWorker;
  51005. }());
  51006. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  51007. var CollisionCoordinatorLegacy = /** @class */ (function () {
  51008. function CollisionCoordinatorLegacy() {
  51009. this._scaledPosition = BABYLON.Vector3.Zero();
  51010. this._scaledVelocity = BABYLON.Vector3.Zero();
  51011. this._finalPosition = BABYLON.Vector3.Zero();
  51012. }
  51013. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  51014. position.divideToRef(collider._radius, this._scaledPosition);
  51015. displacement.divideToRef(collider._radius, this._scaledVelocity);
  51016. collider.collidedMesh = null;
  51017. collider._retry = 0;
  51018. collider._initialVelocity = this._scaledVelocity;
  51019. collider._initialPosition = this._scaledPosition;
  51020. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  51021. this._finalPosition.multiplyInPlace(collider._radius);
  51022. //run the callback
  51023. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  51024. };
  51025. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  51026. this._scene = scene;
  51027. };
  51028. CollisionCoordinatorLegacy.prototype.destroy = function () {
  51029. //Legacy need no destruction method.
  51030. };
  51031. //No update in legacy mode
  51032. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  51033. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  51034. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  51035. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  51036. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  51037. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  51038. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  51039. if (excludedMesh === void 0) { excludedMesh = null; }
  51040. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  51041. if (collider._retry >= maximumRetry) {
  51042. finalPosition.copyFrom(position);
  51043. return;
  51044. }
  51045. // Check if this is a mesh else camera or -1
  51046. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  51047. collider._initialize(position, velocity, closeDistance);
  51048. // Check all meshes
  51049. for (var index = 0; index < this._scene.meshes.length; index++) {
  51050. var mesh = this._scene.meshes[index];
  51051. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  51052. mesh._checkCollision(collider);
  51053. }
  51054. }
  51055. if (!collider.collisionFound) {
  51056. position.addToRef(velocity, finalPosition);
  51057. return;
  51058. }
  51059. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  51060. collider._getResponse(position, velocity);
  51061. }
  51062. if (velocity.length() <= closeDistance) {
  51063. finalPosition.copyFrom(position);
  51064. return;
  51065. }
  51066. collider._retry++;
  51067. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  51068. };
  51069. return CollisionCoordinatorLegacy;
  51070. }());
  51071. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  51072. })(BABYLON || (BABYLON = {}));
  51073. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  51074. var BABYLON;
  51075. (function (BABYLON) {
  51076. /**
  51077. * A particle represents one of the element emitted by a particle system.
  51078. * This is mainly define by its coordinates, direction, velocity and age.
  51079. */
  51080. var Particle = /** @class */ (function () {
  51081. /**
  51082. * Creates a new instance of @see Particle
  51083. * @param particleSystem the particle system the particle belongs to
  51084. */
  51085. function Particle(
  51086. /**
  51087. * particleSystem the particle system the particle belongs to.
  51088. */
  51089. particleSystem) {
  51090. this.particleSystem = particleSystem;
  51091. /**
  51092. * The world position of the particle in the scene.
  51093. */
  51094. this.position = BABYLON.Vector3.Zero();
  51095. /**
  51096. * The world direction of the particle in the scene.
  51097. */
  51098. this.direction = BABYLON.Vector3.Zero();
  51099. /**
  51100. * The color of the particle.
  51101. */
  51102. this.color = new BABYLON.Color4(0, 0, 0, 0);
  51103. /**
  51104. * The color change of the particle per step.
  51105. */
  51106. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  51107. /**
  51108. * Defines how long will the life of the particle be.
  51109. */
  51110. this.lifeTime = 1.0;
  51111. /**
  51112. * The current age of the particle.
  51113. */
  51114. this.age = 0;
  51115. /**
  51116. * The current size of the particle.
  51117. */
  51118. this.size = 0;
  51119. /**
  51120. * The current angle of the particle.
  51121. */
  51122. this.angle = 0;
  51123. /**
  51124. * Defines how fast is the angle changing.
  51125. */
  51126. this.angularSpeed = 0;
  51127. /**
  51128. * Defines the cell index used by the particle to be rendered from a sprite.
  51129. */
  51130. this.cellIndex = 0;
  51131. this._currentFrameCounter = 0;
  51132. if (!this.particleSystem.isAnimationSheetEnabled) {
  51133. return;
  51134. }
  51135. this.updateCellInfoFromSystem();
  51136. }
  51137. Particle.prototype.updateCellInfoFromSystem = function () {
  51138. this.cellIndex = this.particleSystem.startSpriteCellID;
  51139. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  51140. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  51141. }
  51142. else {
  51143. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  51144. }
  51145. };
  51146. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  51147. // (ageOffset / scaledUpdateSpeed) / available cells
  51148. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  51149. this._currentFrameCounter += scaledUpdateSpeed;
  51150. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  51151. this._currentFrameCounter = 0;
  51152. this.cellIndex++;
  51153. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  51154. this.cellIndex = this.particleSystem.endSpriteCellID;
  51155. }
  51156. }
  51157. };
  51158. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  51159. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  51160. this.cellIndex++;
  51161. this._currentFrameCounter = 0;
  51162. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  51163. if (this.particleSystem.spriteCellLoop) {
  51164. this.cellIndex = this.particleSystem.startSpriteCellID;
  51165. }
  51166. else {
  51167. this.cellIndex = this.particleSystem.endSpriteCellID;
  51168. }
  51169. }
  51170. }
  51171. else {
  51172. this._currentFrameCounter++;
  51173. }
  51174. };
  51175. /**
  51176. * Copy the properties of particle to another one.
  51177. * @param other the particle to copy the information to.
  51178. */
  51179. Particle.prototype.copyTo = function (other) {
  51180. other.position.copyFrom(this.position);
  51181. other.direction.copyFrom(this.direction);
  51182. other.color.copyFrom(this.color);
  51183. other.colorStep.copyFrom(this.colorStep);
  51184. other.lifeTime = this.lifeTime;
  51185. other.age = this.age;
  51186. other.size = this.size;
  51187. other.angle = this.angle;
  51188. other.angularSpeed = this.angularSpeed;
  51189. other.particleSystem = this.particleSystem;
  51190. other.cellIndex = this.cellIndex;
  51191. };
  51192. return Particle;
  51193. }());
  51194. BABYLON.Particle = Particle;
  51195. })(BABYLON || (BABYLON = {}));
  51196. //# sourceMappingURL=babylon.particle.js.map
  51197. var BABYLON;
  51198. (function (BABYLON) {
  51199. /**
  51200. * This represents a particle system in Babylon.
  51201. * 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.
  51202. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  51203. * @example https://doc.babylonjs.com/babylon101/particles
  51204. */
  51205. var ParticleSystem = /** @class */ (function () {
  51206. /**
  51207. * Instantiates a particle system.
  51208. * 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.
  51209. * @param name The name of the particle system
  51210. * @param capacity The max number of particles alive at the same time
  51211. * @param scene The scene the particle system belongs to
  51212. * @param customEffect a custom effect used to change the way particles are rendered by default
  51213. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  51214. * @param epsilon Offset used to render the particles
  51215. */
  51216. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  51217. if (customEffect === void 0) { customEffect = null; }
  51218. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  51219. if (epsilon === void 0) { epsilon = 0.01; }
  51220. var _this = this;
  51221. /**
  51222. * List of animations used by the particle system.
  51223. */
  51224. this.animations = [];
  51225. /**
  51226. * The rendering group used by the Particle system to chose when to render.
  51227. */
  51228. this.renderingGroupId = 0;
  51229. /**
  51230. * The emitter represents the Mesh or position we are attaching the particle system to.
  51231. */
  51232. this.emitter = null;
  51233. /**
  51234. * The maximum number of particles to emit per frame
  51235. */
  51236. this.emitRate = 10;
  51237. /**
  51238. * If you want to launch only a few particles at once, that can be done, as well.
  51239. */
  51240. this.manualEmitCount = -1;
  51241. /**
  51242. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  51243. */
  51244. this.updateSpeed = 0.01;
  51245. /**
  51246. * The amount of time the particle system is running (depends of the overall update speed).
  51247. */
  51248. this.targetStopDuration = 0;
  51249. /**
  51250. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  51251. */
  51252. this.disposeOnStop = false;
  51253. /**
  51254. * Minimum power of emitting particles.
  51255. */
  51256. this.minEmitPower = 1;
  51257. /**
  51258. * Maximum power of emitting particles.
  51259. */
  51260. this.maxEmitPower = 1;
  51261. /**
  51262. * Minimum life time of emitting particles.
  51263. */
  51264. this.minLifeTime = 1;
  51265. /**
  51266. * Maximum life time of emitting particles.
  51267. */
  51268. this.maxLifeTime = 1;
  51269. /**
  51270. * Minimum Size of emitting particles.
  51271. */
  51272. this.minSize = 1;
  51273. /**
  51274. * Maximum Size of emitting particles.
  51275. */
  51276. this.maxSize = 1;
  51277. /**
  51278. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  51279. */
  51280. this.minAngularSpeed = 0;
  51281. /**
  51282. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  51283. */
  51284. this.maxAngularSpeed = 0;
  51285. /**
  51286. * The layer mask we are rendering the particles through.
  51287. */
  51288. this.layerMask = 0x0FFFFFFF;
  51289. /**
  51290. * This can help using your own shader to render the particle system.
  51291. * The according effect will be created
  51292. */
  51293. this.customShader = null;
  51294. /**
  51295. * By default particle system starts as soon as they are created. This prevents the
  51296. * automatic start to happen and let you decide when to start emitting particles.
  51297. */
  51298. this.preventAutoStart = false;
  51299. /**
  51300. * Callback triggered when the particle animation is ending.
  51301. */
  51302. this.onAnimationEnd = null;
  51303. /**
  51304. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  51305. */
  51306. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  51307. /**
  51308. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  51309. * to override the particles.
  51310. */
  51311. this.forceDepthWrite = false;
  51312. /**
  51313. * You can use gravity if you want to give an orientation to your particles.
  51314. */
  51315. this.gravity = BABYLON.Vector3.Zero();
  51316. /**
  51317. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51318. */
  51319. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51320. /**
  51321. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51322. */
  51323. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51324. /**
  51325. * Color the particle will have at the end of its lifetime.
  51326. */
  51327. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  51328. /**
  51329. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  51330. */
  51331. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51332. /**
  51333. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  51334. */
  51335. this.spriteCellLoop = true;
  51336. /**
  51337. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  51338. */
  51339. this.spriteCellChangeSpeed = 0;
  51340. /**
  51341. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  51342. */
  51343. this.startSpriteCellID = 0;
  51344. /**
  51345. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  51346. */
  51347. this.endSpriteCellID = 0;
  51348. /**
  51349. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  51350. */
  51351. this.spriteCellWidth = 0;
  51352. /**
  51353. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  51354. */
  51355. this.spriteCellHeight = 0;
  51356. /**
  51357. * An event triggered when the system is disposed.
  51358. */
  51359. this.onDisposeObservable = new BABYLON.Observable();
  51360. this._particles = new Array();
  51361. this._stockParticles = new Array();
  51362. this._newPartsExcess = 0;
  51363. this._vertexBuffers = {};
  51364. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  51365. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  51366. this._scaledDirection = BABYLON.Vector3.Zero();
  51367. this._scaledGravity = BABYLON.Vector3.Zero();
  51368. this._currentRenderId = -1;
  51369. this._started = false;
  51370. this._stopped = false;
  51371. this._actualFrame = 0;
  51372. this._vertexBufferSize = 11;
  51373. // start of sub system methods
  51374. /**
  51375. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  51376. * Its lifetime will start back at 0.
  51377. */
  51378. this.recycleParticle = function (particle) {
  51379. var lastParticle = _this._particles.pop();
  51380. if (lastParticle !== particle) {
  51381. lastParticle.copyTo(particle);
  51382. }
  51383. _this._stockParticles.push(lastParticle);
  51384. };
  51385. this._createParticle = function () {
  51386. var particle;
  51387. if (_this._stockParticles.length !== 0) {
  51388. particle = _this._stockParticles.pop();
  51389. particle.age = 0;
  51390. particle.cellIndex = _this.startSpriteCellID;
  51391. }
  51392. else {
  51393. particle = new BABYLON.Particle(_this);
  51394. }
  51395. return particle;
  51396. };
  51397. this._emitFromParticle = function (particle) {
  51398. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  51399. return;
  51400. }
  51401. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  51402. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  51403. subSystem._rootParticleSystem = _this;
  51404. _this.activeSubSystems.push(subSystem);
  51405. subSystem.start();
  51406. };
  51407. this._appendParticleVertexes = null;
  51408. this.id = name;
  51409. this.name = name;
  51410. this._capacity = capacity;
  51411. this._epsilon = epsilon;
  51412. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  51413. if (isAnimationSheetEnabled) {
  51414. this._vertexBufferSize = 12;
  51415. }
  51416. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51417. this._customEffect = customEffect;
  51418. scene.particleSystems.push(this);
  51419. this._createIndexBuffer();
  51420. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  51421. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  51422. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  51423. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  51424. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  51425. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  51426. if (this._isAnimationSheetEnabled) {
  51427. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  51428. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  51429. }
  51430. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  51431. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  51432. this._vertexBuffers["options"] = options;
  51433. // Default emitter type
  51434. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  51435. this.updateFunction = function (particles) {
  51436. for (var index = 0; index < particles.length; index++) {
  51437. var particle = particles[index];
  51438. particle.age += _this._scaledUpdateSpeed;
  51439. if (particle.age >= particle.lifeTime) {
  51440. _this._emitFromParticle(particle);
  51441. _this.recycleParticle(particle);
  51442. index--;
  51443. continue;
  51444. }
  51445. else {
  51446. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  51447. particle.color.addInPlace(_this._scaledColorStep);
  51448. if (particle.color.a < 0)
  51449. particle.color.a = 0;
  51450. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  51451. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  51452. particle.position.addInPlace(_this._scaledDirection);
  51453. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  51454. particle.direction.addInPlace(_this._scaledGravity);
  51455. if (_this._isAnimationSheetEnabled) {
  51456. particle.updateCellIndex(_this._scaledUpdateSpeed);
  51457. }
  51458. }
  51459. }
  51460. };
  51461. }
  51462. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  51463. /**
  51464. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51465. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51466. */
  51467. get: function () {
  51468. if (this.particleEmitterType.direction1) {
  51469. return this.particleEmitterType.direction1;
  51470. }
  51471. return BABYLON.Vector3.Zero();
  51472. },
  51473. set: function (value) {
  51474. if (this.particleEmitterType.direction1) {
  51475. this.particleEmitterType.direction1 = value;
  51476. }
  51477. },
  51478. enumerable: true,
  51479. configurable: true
  51480. });
  51481. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  51482. /**
  51483. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51484. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51485. */
  51486. get: function () {
  51487. if (this.particleEmitterType.direction2) {
  51488. return this.particleEmitterType.direction2;
  51489. }
  51490. return BABYLON.Vector3.Zero();
  51491. },
  51492. set: function (value) {
  51493. if (this.particleEmitterType.direction2) {
  51494. this.particleEmitterType.direction2 = value;
  51495. }
  51496. },
  51497. enumerable: true,
  51498. configurable: true
  51499. });
  51500. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  51501. /**
  51502. * 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.
  51503. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51504. */
  51505. get: function () {
  51506. if (this.particleEmitterType.minEmitBox) {
  51507. return this.particleEmitterType.minEmitBox;
  51508. }
  51509. return BABYLON.Vector3.Zero();
  51510. },
  51511. set: function (value) {
  51512. if (this.particleEmitterType.minEmitBox) {
  51513. this.particleEmitterType.minEmitBox = value;
  51514. }
  51515. },
  51516. enumerable: true,
  51517. configurable: true
  51518. });
  51519. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  51520. /**
  51521. * 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.
  51522. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51523. */
  51524. get: function () {
  51525. if (this.particleEmitterType.maxEmitBox) {
  51526. return this.particleEmitterType.maxEmitBox;
  51527. }
  51528. return BABYLON.Vector3.Zero();
  51529. },
  51530. set: function (value) {
  51531. if (this.particleEmitterType.maxEmitBox) {
  51532. this.particleEmitterType.maxEmitBox = value;
  51533. }
  51534. },
  51535. enumerable: true,
  51536. configurable: true
  51537. });
  51538. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  51539. /**
  51540. * Sets a callback that will be triggered when the system is disposed.
  51541. */
  51542. set: function (callback) {
  51543. if (this._onDisposeObserver) {
  51544. this.onDisposeObservable.remove(this._onDisposeObserver);
  51545. }
  51546. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  51547. },
  51548. enumerable: true,
  51549. configurable: true
  51550. });
  51551. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  51552. /**
  51553. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  51554. */
  51555. get: function () {
  51556. return this._isAnimationSheetEnabled;
  51557. },
  51558. enumerable: true,
  51559. configurable: true
  51560. });
  51561. Object.defineProperty(ParticleSystem.prototype, "particles", {
  51562. //end of Sub-emitter
  51563. /**
  51564. * Gets the current list of active particles
  51565. */
  51566. get: function () {
  51567. return this._particles;
  51568. },
  51569. enumerable: true,
  51570. configurable: true
  51571. });
  51572. /**
  51573. * Returns the string "ParticleSystem"
  51574. * @returns a string containing the class name
  51575. */
  51576. ParticleSystem.prototype.getClassName = function () {
  51577. return "ParticleSystem";
  51578. };
  51579. ParticleSystem.prototype._createIndexBuffer = function () {
  51580. var indices = [];
  51581. var index = 0;
  51582. for (var count = 0; count < this._capacity; count++) {
  51583. indices.push(index);
  51584. indices.push(index + 1);
  51585. indices.push(index + 2);
  51586. indices.push(index);
  51587. indices.push(index + 2);
  51588. indices.push(index + 3);
  51589. index += 4;
  51590. }
  51591. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  51592. };
  51593. /**
  51594. * Gets the maximum number of particles active at the same time.
  51595. * @returns The max number of active particles.
  51596. */
  51597. ParticleSystem.prototype.getCapacity = function () {
  51598. return this._capacity;
  51599. };
  51600. /**
  51601. * Gets Wether there are still active particles in the system.
  51602. * @returns True if it is alive, otherwise false.
  51603. */
  51604. ParticleSystem.prototype.isAlive = function () {
  51605. return this._alive;
  51606. };
  51607. /**
  51608. * Gets Wether the system has been started.
  51609. * @returns True if it has been started, otherwise false.
  51610. */
  51611. ParticleSystem.prototype.isStarted = function () {
  51612. return this._started;
  51613. };
  51614. /**
  51615. * Starts the particle system and begins to emit.
  51616. */
  51617. ParticleSystem.prototype.start = function () {
  51618. this._started = true;
  51619. this._stopped = false;
  51620. this._actualFrame = 0;
  51621. if (this.subEmitters && this.subEmitters.length != 0) {
  51622. this.activeSubSystems = new Array();
  51623. }
  51624. };
  51625. /**
  51626. * Stops the particle system.
  51627. * @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.
  51628. */
  51629. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  51630. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  51631. this._stopped = true;
  51632. if (stopSubEmitters) {
  51633. this._stopSubEmitters();
  51634. }
  51635. };
  51636. // animation sheet
  51637. /**
  51638. * Remove all active particles
  51639. */
  51640. ParticleSystem.prototype.reset = function () {
  51641. this._stockParticles = [];
  51642. this._particles = [];
  51643. };
  51644. /**
  51645. * @ignore (for internal use only)
  51646. */
  51647. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  51648. var offset = index * this._vertexBufferSize;
  51649. this._vertexData[offset] = particle.position.x;
  51650. this._vertexData[offset + 1] = particle.position.y;
  51651. this._vertexData[offset + 2] = particle.position.z;
  51652. this._vertexData[offset + 3] = particle.color.r;
  51653. this._vertexData[offset + 4] = particle.color.g;
  51654. this._vertexData[offset + 5] = particle.color.b;
  51655. this._vertexData[offset + 6] = particle.color.a;
  51656. this._vertexData[offset + 7] = particle.angle;
  51657. this._vertexData[offset + 8] = particle.size;
  51658. this._vertexData[offset + 9] = offsetX;
  51659. this._vertexData[offset + 10] = offsetY;
  51660. };
  51661. /**
  51662. * @ignore (for internal use only)
  51663. */
  51664. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  51665. if (offsetX === 0)
  51666. offsetX = this._epsilon;
  51667. else if (offsetX === 1)
  51668. offsetX = 1 - this._epsilon;
  51669. if (offsetY === 0)
  51670. offsetY = this._epsilon;
  51671. else if (offsetY === 1)
  51672. offsetY = 1 - this._epsilon;
  51673. var offset = index * this._vertexBufferSize;
  51674. this._vertexData[offset] = particle.position.x;
  51675. this._vertexData[offset + 1] = particle.position.y;
  51676. this._vertexData[offset + 2] = particle.position.z;
  51677. this._vertexData[offset + 3] = particle.color.r;
  51678. this._vertexData[offset + 4] = particle.color.g;
  51679. this._vertexData[offset + 5] = particle.color.b;
  51680. this._vertexData[offset + 6] = particle.color.a;
  51681. this._vertexData[offset + 7] = particle.angle;
  51682. this._vertexData[offset + 8] = particle.size;
  51683. this._vertexData[offset + 9] = offsetX;
  51684. this._vertexData[offset + 10] = offsetY;
  51685. this._vertexData[offset + 11] = particle.cellIndex;
  51686. };
  51687. ParticleSystem.prototype._stopSubEmitters = function () {
  51688. if (!this.activeSubSystems) {
  51689. return;
  51690. }
  51691. this.activeSubSystems.forEach(function (subSystem) {
  51692. subSystem.stop(true);
  51693. });
  51694. this.activeSubSystems = new Array();
  51695. };
  51696. ParticleSystem.prototype._removeFromRoot = function () {
  51697. if (!this._rootParticleSystem) {
  51698. return;
  51699. }
  51700. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  51701. if (index !== -1) {
  51702. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  51703. }
  51704. };
  51705. // end of sub system methods
  51706. ParticleSystem.prototype._update = function (newParticles) {
  51707. // Update current
  51708. this._alive = this._particles.length > 0;
  51709. this.updateFunction(this._particles);
  51710. // Add new ones
  51711. var worldMatrix;
  51712. if (this.emitter.position) {
  51713. var emitterMesh = this.emitter;
  51714. worldMatrix = emitterMesh.getWorldMatrix();
  51715. }
  51716. else {
  51717. var emitterPosition = this.emitter;
  51718. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  51719. }
  51720. var particle;
  51721. for (var index = 0; index < newParticles; index++) {
  51722. if (this._particles.length === this._capacity) {
  51723. break;
  51724. }
  51725. particle = this._createParticle();
  51726. this._particles.push(particle);
  51727. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  51728. if (this.startPositionFunction) {
  51729. this.startPositionFunction(worldMatrix, particle.position, particle);
  51730. }
  51731. else {
  51732. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  51733. }
  51734. if (this.startDirectionFunction) {
  51735. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51736. }
  51737. else {
  51738. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51739. }
  51740. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  51741. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  51742. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  51743. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  51744. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  51745. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  51746. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  51747. }
  51748. };
  51749. ParticleSystem.prototype._getEffect = function () {
  51750. if (this._customEffect) {
  51751. return this._customEffect;
  51752. }
  51753. ;
  51754. var defines = [];
  51755. if (this._scene.clipPlane) {
  51756. defines.push("#define CLIPPLANE");
  51757. }
  51758. if (this._isAnimationSheetEnabled) {
  51759. defines.push("#define ANIMATESHEET");
  51760. }
  51761. // Effect
  51762. var join = defines.join("\n");
  51763. if (this._cachedDefines !== join) {
  51764. this._cachedDefines = join;
  51765. var attributesNamesOrOptions;
  51766. var effectCreationOption;
  51767. if (this._isAnimationSheetEnabled) {
  51768. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  51769. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  51770. }
  51771. else {
  51772. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  51773. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  51774. }
  51775. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  51776. }
  51777. return this._effect;
  51778. };
  51779. /**
  51780. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  51781. */
  51782. ParticleSystem.prototype.animate = function () {
  51783. if (!this._started)
  51784. return;
  51785. var effect = this._getEffect();
  51786. // Check
  51787. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  51788. return;
  51789. if (this._currentRenderId === this._scene.getRenderId()) {
  51790. return;
  51791. }
  51792. this._currentRenderId = this._scene.getRenderId();
  51793. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  51794. // determine the number of particles we need to create
  51795. var newParticles;
  51796. if (this.manualEmitCount > -1) {
  51797. newParticles = this.manualEmitCount;
  51798. this._newPartsExcess = 0;
  51799. this.manualEmitCount = 0;
  51800. }
  51801. else {
  51802. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  51803. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  51804. }
  51805. if (this._newPartsExcess > 1.0) {
  51806. newParticles += this._newPartsExcess >> 0;
  51807. this._newPartsExcess -= this._newPartsExcess >> 0;
  51808. }
  51809. this._alive = false;
  51810. if (!this._stopped) {
  51811. this._actualFrame += this._scaledUpdateSpeed;
  51812. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  51813. this.stop();
  51814. }
  51815. else {
  51816. newParticles = 0;
  51817. }
  51818. this._update(newParticles);
  51819. // Stopped?
  51820. if (this._stopped) {
  51821. if (!this._alive) {
  51822. this._started = false;
  51823. if (this.onAnimationEnd) {
  51824. this.onAnimationEnd();
  51825. }
  51826. if (this.disposeOnStop) {
  51827. this._scene._toBeDisposed.push(this);
  51828. }
  51829. }
  51830. }
  51831. // Animation sheet
  51832. if (this._isAnimationSheetEnabled) {
  51833. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  51834. }
  51835. else {
  51836. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  51837. }
  51838. // Update VBO
  51839. var offset = 0;
  51840. for (var index = 0; index < this._particles.length; index++) {
  51841. var particle = this._particles[index];
  51842. this._appendParticleVertexes(offset, particle);
  51843. offset += 4;
  51844. }
  51845. if (this._vertexBuffer) {
  51846. this._vertexBuffer.update(this._vertexData);
  51847. }
  51848. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  51849. this.stop();
  51850. }
  51851. };
  51852. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  51853. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  51854. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  51855. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  51856. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  51857. };
  51858. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  51859. this._appendParticleVertex(offset++, particle, 0, 0);
  51860. this._appendParticleVertex(offset++, particle, 1, 0);
  51861. this._appendParticleVertex(offset++, particle, 1, 1);
  51862. this._appendParticleVertex(offset++, particle, 0, 1);
  51863. };
  51864. /**
  51865. * Rebuilds the particle system.
  51866. */
  51867. ParticleSystem.prototype.rebuild = function () {
  51868. this._createIndexBuffer();
  51869. if (this._vertexBuffer) {
  51870. this._vertexBuffer._rebuild();
  51871. }
  51872. };
  51873. /**
  51874. * Is this system ready to be used/rendered
  51875. * @return true if the system is ready
  51876. */
  51877. ParticleSystem.prototype.isReady = function () {
  51878. var effect = this._getEffect();
  51879. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  51880. return false;
  51881. }
  51882. return true;
  51883. };
  51884. /**
  51885. * Renders the particle system in its current state.
  51886. * @returns the current number of particles
  51887. */
  51888. ParticleSystem.prototype.render = function () {
  51889. var effect = this._getEffect();
  51890. // Check
  51891. if (!this.isReady() || !this._particles.length) {
  51892. return 0;
  51893. }
  51894. var engine = this._scene.getEngine();
  51895. // Render
  51896. engine.enableEffect(effect);
  51897. engine.setState(false);
  51898. var viewMatrix = this._scene.getViewMatrix();
  51899. effect.setTexture("diffuseSampler", this.particleTexture);
  51900. effect.setMatrix("view", viewMatrix);
  51901. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  51902. if (this._isAnimationSheetEnabled && this.particleTexture) {
  51903. var baseSize = this.particleTexture.getBaseSize();
  51904. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  51905. }
  51906. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  51907. if (this._scene.clipPlane) {
  51908. var clipPlane = this._scene.clipPlane;
  51909. var invView = viewMatrix.clone();
  51910. invView.invert();
  51911. effect.setMatrix("invView", invView);
  51912. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  51913. }
  51914. // VBOs
  51915. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  51916. // Draw order
  51917. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  51918. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  51919. }
  51920. else {
  51921. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  51922. }
  51923. if (this.forceDepthWrite) {
  51924. engine.setDepthWrite(true);
  51925. }
  51926. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  51927. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  51928. return this._particles.length;
  51929. };
  51930. /**
  51931. * Disposes the particle system and free the associated resources
  51932. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  51933. */
  51934. ParticleSystem.prototype.dispose = function (disposeTexture) {
  51935. if (disposeTexture === void 0) { disposeTexture = true; }
  51936. if (this._vertexBuffer) {
  51937. this._vertexBuffer.dispose();
  51938. this._vertexBuffer = null;
  51939. }
  51940. if (this._indexBuffer) {
  51941. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  51942. this._indexBuffer = null;
  51943. }
  51944. if (disposeTexture && this.particleTexture) {
  51945. this.particleTexture.dispose();
  51946. this.particleTexture = null;
  51947. }
  51948. this._removeFromRoot();
  51949. // Remove from scene
  51950. var index = this._scene.particleSystems.indexOf(this);
  51951. if (index > -1) {
  51952. this._scene.particleSystems.splice(index, 1);
  51953. }
  51954. // Callback
  51955. this.onDisposeObservable.notifyObservers(this);
  51956. this.onDisposeObservable.clear();
  51957. };
  51958. /**
  51959. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  51960. * @param radius The radius of the sphere to emit from
  51961. * @returns the emitter
  51962. */
  51963. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  51964. if (radius === void 0) { radius = 1; }
  51965. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  51966. this.particleEmitterType = particleEmitter;
  51967. return particleEmitter;
  51968. };
  51969. /**
  51970. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  51971. * @param radius The radius of the sphere to emit from
  51972. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  51973. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  51974. * @returns the emitter
  51975. */
  51976. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  51977. if (radius === void 0) { radius = 1; }
  51978. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  51979. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  51980. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  51981. this.particleEmitterType = particleEmitter;
  51982. return particleEmitter;
  51983. };
  51984. /**
  51985. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  51986. * @param radius The radius of the cone to emit from
  51987. * @param angle The base angle of the cone
  51988. * @returns the emitter
  51989. */
  51990. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  51991. if (radius === void 0) { radius = 1; }
  51992. if (angle === void 0) { angle = Math.PI / 4; }
  51993. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  51994. this.particleEmitterType = particleEmitter;
  51995. return particleEmitter;
  51996. };
  51997. // 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.
  51998. /**
  51999. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  52000. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  52001. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  52002. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  52003. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  52004. * @returns the emitter
  52005. */
  52006. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  52007. var particleEmitter = new BABYLON.BoxParticleEmitter();
  52008. this.direction1 = direction1;
  52009. this.direction2 = direction2;
  52010. this.minEmitBox = minEmitBox;
  52011. this.maxEmitBox = maxEmitBox;
  52012. this.particleEmitterType = particleEmitter;
  52013. return particleEmitter;
  52014. };
  52015. // Clone
  52016. /**
  52017. * Clones the particle system.
  52018. * @param name The name of the cloned object
  52019. * @param newEmitter The new emitter to use
  52020. * @returns the cloned particle system
  52021. */
  52022. ParticleSystem.prototype.clone = function (name, newEmitter) {
  52023. var custom = null;
  52024. var program = null;
  52025. if (this.customShader != null) {
  52026. program = this.customShader;
  52027. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  52028. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  52029. }
  52030. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  52031. result.customShader = program;
  52032. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  52033. if (newEmitter === undefined) {
  52034. newEmitter = this.emitter;
  52035. }
  52036. result.emitter = newEmitter;
  52037. if (this.particleTexture) {
  52038. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  52039. }
  52040. if (!this.preventAutoStart) {
  52041. result.start();
  52042. }
  52043. return result;
  52044. };
  52045. /**
  52046. * Serializes the particle system to a JSON object.
  52047. * @returns the JSON object
  52048. */
  52049. ParticleSystem.prototype.serialize = function () {
  52050. var serializationObject = {};
  52051. serializationObject.name = this.name;
  52052. serializationObject.id = this.id;
  52053. // Emitter
  52054. if (this.emitter.position) {
  52055. var emitterMesh = this.emitter;
  52056. serializationObject.emitterId = emitterMesh.id;
  52057. }
  52058. else {
  52059. var emitterPosition = this.emitter;
  52060. serializationObject.emitter = emitterPosition.asArray();
  52061. }
  52062. serializationObject.capacity = this.getCapacity();
  52063. if (this.particleTexture) {
  52064. serializationObject.textureName = this.particleTexture.name;
  52065. }
  52066. // Animations
  52067. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  52068. // Particle system
  52069. serializationObject.minAngularSpeed = this.minAngularSpeed;
  52070. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  52071. serializationObject.minSize = this.minSize;
  52072. serializationObject.maxSize = this.maxSize;
  52073. serializationObject.minEmitPower = this.minEmitPower;
  52074. serializationObject.maxEmitPower = this.maxEmitPower;
  52075. serializationObject.minLifeTime = this.minLifeTime;
  52076. serializationObject.maxLifeTime = this.maxLifeTime;
  52077. serializationObject.emitRate = this.emitRate;
  52078. serializationObject.minEmitBox = this.minEmitBox.asArray();
  52079. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  52080. serializationObject.gravity = this.gravity.asArray();
  52081. serializationObject.direction1 = this.direction1.asArray();
  52082. serializationObject.direction2 = this.direction2.asArray();
  52083. serializationObject.color1 = this.color1.asArray();
  52084. serializationObject.color2 = this.color2.asArray();
  52085. serializationObject.colorDead = this.colorDead.asArray();
  52086. serializationObject.updateSpeed = this.updateSpeed;
  52087. serializationObject.targetStopDuration = this.targetStopDuration;
  52088. serializationObject.textureMask = this.textureMask.asArray();
  52089. serializationObject.blendMode = this.blendMode;
  52090. serializationObject.customShader = this.customShader;
  52091. serializationObject.preventAutoStart = this.preventAutoStart;
  52092. serializationObject.startSpriteCellID = this.startSpriteCellID;
  52093. serializationObject.endSpriteCellID = this.endSpriteCellID;
  52094. serializationObject.spriteCellLoop = this.spriteCellLoop;
  52095. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  52096. serializationObject.spriteCellWidth = this.spriteCellWidth;
  52097. serializationObject.spriteCellHeight = this.spriteCellHeight;
  52098. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  52099. // Emitter
  52100. if (this.particleEmitterType) {
  52101. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  52102. }
  52103. return serializationObject;
  52104. };
  52105. /**
  52106. * Parses a JSON object to create a particle system.
  52107. * @param parsedParticleSystem The JSON object to parse
  52108. * @param scene The scene to create the particle system in
  52109. * @param rootUrl The root url to use to load external dependencies like texture
  52110. * @returns the Parsed particle system
  52111. */
  52112. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  52113. var name = parsedParticleSystem.name;
  52114. var custom = null;
  52115. var program = null;
  52116. if (parsedParticleSystem.customShader) {
  52117. program = parsedParticleSystem.customShader;
  52118. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  52119. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  52120. }
  52121. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  52122. particleSystem.customShader = program;
  52123. if (parsedParticleSystem.id) {
  52124. particleSystem.id = parsedParticleSystem.id;
  52125. }
  52126. // Auto start
  52127. if (parsedParticleSystem.preventAutoStart) {
  52128. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  52129. }
  52130. // Texture
  52131. if (parsedParticleSystem.textureName) {
  52132. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  52133. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  52134. }
  52135. // Emitter
  52136. if (parsedParticleSystem.emitterId) {
  52137. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  52138. }
  52139. else {
  52140. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  52141. }
  52142. // Animations
  52143. if (parsedParticleSystem.animations) {
  52144. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  52145. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  52146. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  52147. }
  52148. }
  52149. if (parsedParticleSystem.autoAnimate) {
  52150. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  52151. }
  52152. // Particle system
  52153. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  52154. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  52155. particleSystem.minSize = parsedParticleSystem.minSize;
  52156. particleSystem.maxSize = parsedParticleSystem.maxSize;
  52157. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  52158. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  52159. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  52160. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  52161. particleSystem.emitRate = parsedParticleSystem.emitRate;
  52162. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  52163. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  52164. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  52165. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  52166. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  52167. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  52168. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  52169. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  52170. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  52171. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  52172. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  52173. particleSystem.blendMode = parsedParticleSystem.blendMode;
  52174. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  52175. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  52176. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  52177. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  52178. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  52179. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  52180. if (!particleSystem.preventAutoStart) {
  52181. particleSystem.start();
  52182. }
  52183. return particleSystem;
  52184. };
  52185. /**
  52186. * Source color is added to the destination color without alpha affecting the result.
  52187. */
  52188. ParticleSystem.BLENDMODE_ONEONE = 0;
  52189. /**
  52190. * Blend current color and particle color using particle’s alpha.
  52191. */
  52192. ParticleSystem.BLENDMODE_STANDARD = 1;
  52193. return ParticleSystem;
  52194. }());
  52195. BABYLON.ParticleSystem = ParticleSystem;
  52196. })(BABYLON || (BABYLON = {}));
  52197. //# sourceMappingURL=babylon.particleSystem.js.map
  52198. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  52199. var BABYLON;
  52200. (function (BABYLON) {
  52201. /**
  52202. * Particle emitter emitting particles from the inside of a box.
  52203. * It emits the particles randomly between 2 given directions.
  52204. */
  52205. var BoxParticleEmitter = /** @class */ (function () {
  52206. /**
  52207. * Creates a new instance of @see BoxParticleEmitter
  52208. */
  52209. function BoxParticleEmitter() {
  52210. /**
  52211. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52212. */
  52213. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  52214. /**
  52215. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52216. */
  52217. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  52218. /**
  52219. * 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.
  52220. */
  52221. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  52222. /**
  52223. * 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.
  52224. */
  52225. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  52226. }
  52227. /**
  52228. * Called by the particle System when the direction is computed for the created particle.
  52229. * @param emitPower is the power of the particle (speed)
  52230. * @param worldMatrix is the world matrix of the particle system
  52231. * @param directionToUpdate is the direction vector to update with the result
  52232. * @param particle is the particle we are computed the direction for
  52233. */
  52234. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52235. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52236. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52237. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52238. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52239. };
  52240. /**
  52241. * Called by the particle System when the position is computed for the created particle.
  52242. * @param worldMatrix is the world matrix of the particle system
  52243. * @param positionToUpdate is the position vector to update with the result
  52244. * @param particle is the particle we are computed the position for
  52245. */
  52246. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52247. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  52248. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  52249. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  52250. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52251. };
  52252. /**
  52253. * Clones the current emitter and returns a copy of it
  52254. * @returns the new emitter
  52255. */
  52256. BoxParticleEmitter.prototype.clone = function () {
  52257. var newOne = new BoxParticleEmitter();
  52258. BABYLON.Tools.DeepCopy(this, newOne);
  52259. return newOne;
  52260. };
  52261. /**
  52262. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52263. * @param effect defines the update shader
  52264. */
  52265. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  52266. effect.setVector3("direction1", this.direction1);
  52267. effect.setVector3("direction2", this.direction2);
  52268. effect.setVector3("minEmitBox", this.minEmitBox);
  52269. effect.setVector3("maxEmitBox", this.maxEmitBox);
  52270. };
  52271. /**
  52272. * Returns a string to use to update the GPU particles update shader
  52273. * @returns a string containng the defines string
  52274. */
  52275. BoxParticleEmitter.prototype.getEffectDefines = function () {
  52276. return "#define BOXEMITTER";
  52277. };
  52278. /**
  52279. * Returns the string "BoxEmitter"
  52280. * @returns a string containing the class name
  52281. */
  52282. BoxParticleEmitter.prototype.getClassName = function () {
  52283. return "BoxEmitter";
  52284. };
  52285. /**
  52286. * Serializes the particle system to a JSON object.
  52287. * @returns the JSON object
  52288. */
  52289. BoxParticleEmitter.prototype.serialize = function () {
  52290. var serializationObject = {};
  52291. serializationObject.type = this.getClassName();
  52292. serializationObject.direction1 = this.direction1.asArray();
  52293. ;
  52294. serializationObject.direction2 = this.direction2.asArray();
  52295. ;
  52296. serializationObject.minEmitBox = this.minEmitBox.asArray();
  52297. ;
  52298. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  52299. ;
  52300. return serializationObject;
  52301. };
  52302. /**
  52303. * Parse properties from a JSON object
  52304. * @param serializationObject defines the JSON object
  52305. */
  52306. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  52307. this.direction1.copyFrom(serializationObject.direction1);
  52308. this.direction2.copyFrom(serializationObject.direction2);
  52309. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  52310. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  52311. };
  52312. return BoxParticleEmitter;
  52313. }());
  52314. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  52315. })(BABYLON || (BABYLON = {}));
  52316. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  52317. var BABYLON;
  52318. (function (BABYLON) {
  52319. /**
  52320. * Particle emitter emitting particles from the inside of a cone.
  52321. * It emits the particles alongside the cone volume from the base to the particle.
  52322. * The emission direction might be randomized.
  52323. */
  52324. var ConeParticleEmitter = /** @class */ (function () {
  52325. /**
  52326. * Creates a new instance of @see ConeParticleEmitter
  52327. * @param radius the radius of the emission cone (1 by default)
  52328. * @param angles the cone base angle (PI by default)
  52329. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52330. */
  52331. function ConeParticleEmitter(radius,
  52332. /**
  52333. * The radius of the emission cone.
  52334. */
  52335. angle,
  52336. /**
  52337. * The cone base angle.
  52338. */
  52339. directionRandomizer) {
  52340. if (radius === void 0) { radius = 1; }
  52341. if (angle === void 0) { angle = Math.PI; }
  52342. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52343. this.angle = angle;
  52344. this.directionRandomizer = directionRandomizer;
  52345. this.radius = radius;
  52346. }
  52347. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  52348. /**
  52349. * Gets the radius of the emission cone.
  52350. */
  52351. get: function () {
  52352. return this._radius;
  52353. },
  52354. /**
  52355. * Sets the radius of the emission cone.
  52356. */
  52357. set: function (value) {
  52358. this._radius = value;
  52359. if (this.angle !== 0) {
  52360. this._height = value / Math.tan(this.angle / 2);
  52361. }
  52362. else {
  52363. this._height = 1;
  52364. }
  52365. },
  52366. enumerable: true,
  52367. configurable: true
  52368. });
  52369. /**
  52370. * Called by the particle System when the direction is computed for the created particle.
  52371. * @param emitPower is the power of the particle (speed)
  52372. * @param worldMatrix is the world matrix of the particle system
  52373. * @param directionToUpdate is the direction vector to update with the result
  52374. * @param particle is the particle we are computed the direction for
  52375. */
  52376. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52377. if (this.angle === 0) {
  52378. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  52379. }
  52380. else {
  52381. // measure the direction Vector from the emitter to the particle.
  52382. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52383. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52384. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52385. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52386. direction.x += randX;
  52387. direction.y += randY;
  52388. direction.z += randZ;
  52389. direction.normalize();
  52390. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52391. }
  52392. };
  52393. /**
  52394. * Called by the particle System when the position is computed for the created particle.
  52395. * @param worldMatrix is the world matrix of the particle system
  52396. * @param positionToUpdate is the position vector to update with the result
  52397. * @param particle is the particle we are computed the position for
  52398. */
  52399. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52400. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  52401. var h = BABYLON.Scalar.RandomRange(0, 1);
  52402. // Better distribution in a cone at normal angles.
  52403. h = 1 - h * h;
  52404. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  52405. radius = radius * h / this._height;
  52406. var randX = radius * Math.sin(s);
  52407. var randZ = radius * Math.cos(s);
  52408. var randY = h * this._height;
  52409. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52410. };
  52411. /**
  52412. * Clones the current emitter and returns a copy of it
  52413. * @returns the new emitter
  52414. */
  52415. ConeParticleEmitter.prototype.clone = function () {
  52416. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  52417. BABYLON.Tools.DeepCopy(this, newOne);
  52418. return newOne;
  52419. };
  52420. /**
  52421. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52422. * @param effect defines the update shader
  52423. */
  52424. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  52425. effect.setFloat("radius", this.radius);
  52426. effect.setFloat("angle", this.angle);
  52427. effect.setFloat("height", this._height);
  52428. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52429. };
  52430. /**
  52431. * Returns a string to use to update the GPU particles update shader
  52432. * @returns a string containng the defines string
  52433. */
  52434. ConeParticleEmitter.prototype.getEffectDefines = function () {
  52435. return "#define CONEEMITTER";
  52436. };
  52437. /**
  52438. * Returns the string "BoxEmitter"
  52439. * @returns a string containing the class name
  52440. */
  52441. ConeParticleEmitter.prototype.getClassName = function () {
  52442. return "ConeEmitter";
  52443. };
  52444. /**
  52445. * Serializes the particle system to a JSON object.
  52446. * @returns the JSON object
  52447. */
  52448. ConeParticleEmitter.prototype.serialize = function () {
  52449. var serializationObject = {};
  52450. serializationObject.type = this.getClassName();
  52451. serializationObject.radius = this.radius;
  52452. serializationObject.angle = this.angle;
  52453. serializationObject.directionRandomizer = this.directionRandomizer;
  52454. return serializationObject;
  52455. };
  52456. /**
  52457. * Parse properties from a JSON object
  52458. * @param serializationObject defines the JSON object
  52459. */
  52460. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  52461. this.radius = serializationObject.radius;
  52462. this.angle = serializationObject.angle;
  52463. this.directionRandomizer = serializationObject.directionRandomizer;
  52464. };
  52465. return ConeParticleEmitter;
  52466. }());
  52467. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  52468. })(BABYLON || (BABYLON = {}));
  52469. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  52470. var BABYLON;
  52471. (function (BABYLON) {
  52472. /**
  52473. * Particle emitter emitting particles from the inside of a sphere.
  52474. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  52475. */
  52476. var SphereParticleEmitter = /** @class */ (function () {
  52477. /**
  52478. * Creates a new instance of @see SphereParticleEmitter
  52479. * @param radius the radius of the emission sphere (1 by default)
  52480. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52481. */
  52482. function SphereParticleEmitter(
  52483. /**
  52484. * The radius of the emission sphere.
  52485. */
  52486. radius,
  52487. /**
  52488. * How much to randomize the particle direction [0-1].
  52489. */
  52490. directionRandomizer) {
  52491. if (radius === void 0) { radius = 1; }
  52492. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52493. this.radius = radius;
  52494. this.directionRandomizer = directionRandomizer;
  52495. }
  52496. /**
  52497. * Called by the particle System when the direction is computed for the created particle.
  52498. * @param emitPower is the power of the particle (speed)
  52499. * @param worldMatrix is the world matrix of the particle system
  52500. * @param directionToUpdate is the direction vector to update with the result
  52501. * @param particle is the particle we are computed the direction for
  52502. */
  52503. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52504. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52505. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52506. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52507. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52508. direction.x += randX;
  52509. direction.y += randY;
  52510. direction.z += randZ;
  52511. direction.normalize();
  52512. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52513. };
  52514. /**
  52515. * Called by the particle System when the position is computed for the created particle.
  52516. * @param worldMatrix is the world matrix of the particle system
  52517. * @param positionToUpdate is the position vector to update with the result
  52518. * @param particle is the particle we are computed the position for
  52519. */
  52520. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52521. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  52522. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  52523. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  52524. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  52525. var randY = randRadius * Math.cos(theta);
  52526. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  52527. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52528. };
  52529. /**
  52530. * Clones the current emitter and returns a copy of it
  52531. * @returns the new emitter
  52532. */
  52533. SphereParticleEmitter.prototype.clone = function () {
  52534. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  52535. BABYLON.Tools.DeepCopy(this, newOne);
  52536. return newOne;
  52537. };
  52538. /**
  52539. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52540. * @param effect defines the update shader
  52541. */
  52542. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  52543. effect.setFloat("radius", this.radius);
  52544. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52545. };
  52546. /**
  52547. * Returns a string to use to update the GPU particles update shader
  52548. * @returns a string containng the defines string
  52549. */
  52550. SphereParticleEmitter.prototype.getEffectDefines = function () {
  52551. return "#define SPHEREEMITTER";
  52552. };
  52553. /**
  52554. * Returns the string "SphereParticleEmitter"
  52555. * @returns a string containing the class name
  52556. */
  52557. SphereParticleEmitter.prototype.getClassName = function () {
  52558. return "SphereParticleEmitter";
  52559. };
  52560. /**
  52561. * Serializes the particle system to a JSON object.
  52562. * @returns the JSON object
  52563. */
  52564. SphereParticleEmitter.prototype.serialize = function () {
  52565. var serializationObject = {};
  52566. serializationObject.type = this.getClassName();
  52567. serializationObject.radius = this.radius;
  52568. serializationObject.directionRandomizer = this.directionRandomizer;
  52569. return serializationObject;
  52570. };
  52571. /**
  52572. * Parse properties from a JSON object
  52573. * @param serializationObject defines the JSON object
  52574. */
  52575. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  52576. this.radius = serializationObject.radius;
  52577. this.directionRandomizer = serializationObject.directionRandomizer;
  52578. };
  52579. return SphereParticleEmitter;
  52580. }());
  52581. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  52582. /**
  52583. * Particle emitter emitting particles from the inside of a sphere.
  52584. * It emits the particles randomly between two vectors.
  52585. */
  52586. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  52587. __extends(SphereDirectedParticleEmitter, _super);
  52588. /**
  52589. * Creates a new instance of @see SphereDirectedParticleEmitter
  52590. * @param radius the radius of the emission sphere (1 by default)
  52591. * @param direction1 the min limit of the emission direction (up vector by default)
  52592. * @param direction2 the max limit of the emission direction (up vector by default)
  52593. */
  52594. function SphereDirectedParticleEmitter(radius,
  52595. /**
  52596. * The min limit of the emission direction.
  52597. */
  52598. direction1,
  52599. /**
  52600. * The max limit of the emission direction.
  52601. */
  52602. direction2) {
  52603. if (radius === void 0) { radius = 1; }
  52604. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  52605. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  52606. var _this = _super.call(this, radius) || this;
  52607. _this.direction1 = direction1;
  52608. _this.direction2 = direction2;
  52609. return _this;
  52610. }
  52611. /**
  52612. * Called by the particle System when the direction is computed for the created particle.
  52613. * @param emitPower is the power of the particle (speed)
  52614. * @param worldMatrix is the world matrix of the particle system
  52615. * @param directionToUpdate is the direction vector to update with the result
  52616. * @param particle is the particle we are computed the direction for
  52617. */
  52618. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52619. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52620. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52621. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52622. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52623. };
  52624. /**
  52625. * Clones the current emitter and returns a copy of it
  52626. * @returns the new emitter
  52627. */
  52628. SphereDirectedParticleEmitter.prototype.clone = function () {
  52629. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  52630. BABYLON.Tools.DeepCopy(this, newOne);
  52631. return newOne;
  52632. };
  52633. /**
  52634. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52635. * @param effect defines the update shader
  52636. */
  52637. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  52638. effect.setFloat("radius", this.radius);
  52639. effect.setVector3("direction1", this.direction1);
  52640. effect.setVector3("direction2", this.direction2);
  52641. };
  52642. /**
  52643. * Returns a string to use to update the GPU particles update shader
  52644. * @returns a string containng the defines string
  52645. */
  52646. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  52647. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  52648. };
  52649. /**
  52650. * Returns the string "SphereDirectedParticleEmitter"
  52651. * @returns a string containing the class name
  52652. */
  52653. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  52654. return "SphereDirectedParticleEmitter";
  52655. };
  52656. /**
  52657. * Serializes the particle system to a JSON object.
  52658. * @returns the JSON object
  52659. */
  52660. SphereDirectedParticleEmitter.prototype.serialize = function () {
  52661. var serializationObject = _super.prototype.serialize.call(this);
  52662. ;
  52663. serializationObject.direction1 = this.direction1.asArray();
  52664. ;
  52665. serializationObject.direction2 = this.direction2.asArray();
  52666. ;
  52667. return serializationObject;
  52668. };
  52669. /**
  52670. * Parse properties from a JSON object
  52671. * @param serializationObject defines the JSON object
  52672. */
  52673. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  52674. _super.prototype.parse.call(this, serializationObject);
  52675. this.direction1.copyFrom(serializationObject.direction1);
  52676. this.direction2.copyFrom(serializationObject.direction2);
  52677. };
  52678. return SphereDirectedParticleEmitter;
  52679. }(SphereParticleEmitter));
  52680. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  52681. })(BABYLON || (BABYLON = {}));
  52682. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  52683. var __assign = (this && this.__assign) || Object.assign || function(t) {
  52684. for (var s, i = 1, n = arguments.length; i < n; i++) {
  52685. s = arguments[i];
  52686. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  52687. t[p] = s[p];
  52688. }
  52689. return t;
  52690. };
  52691. var BABYLON;
  52692. (function (BABYLON) {
  52693. /**
  52694. * This represents a GPU particle system in Babylon
  52695. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  52696. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  52697. */
  52698. var GPUParticleSystem = /** @class */ (function () {
  52699. /**
  52700. * Instantiates a GPU particle system.
  52701. * 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.
  52702. * @param name The name of the particle system
  52703. * @param capacity The max number of particles alive at the same time
  52704. * @param scene The scene the particle system belongs to
  52705. */
  52706. function GPUParticleSystem(name, options, scene) {
  52707. /**
  52708. * The emitter represents the Mesh or position we are attaching the particle system to.
  52709. */
  52710. this.emitter = null;
  52711. /**
  52712. * The rendering group used by the Particle system to chose when to render.
  52713. */
  52714. this.renderingGroupId = 0;
  52715. /**
  52716. * The layer mask we are rendering the particles through.
  52717. */
  52718. this.layerMask = 0x0FFFFFFF;
  52719. this._targetIndex = 0;
  52720. this._currentRenderId = -1;
  52721. this._started = false;
  52722. this._stopped = false;
  52723. this._timeDelta = 0;
  52724. this._attributesStrideSize = 14;
  52725. this._actualFrame = 0;
  52726. /**
  52727. * List of animations used by the particle system.
  52728. */
  52729. this.animations = [];
  52730. /**
  52731. * An event triggered when the system is disposed.
  52732. */
  52733. this.onDisposeObservable = new BABYLON.Observable();
  52734. /**
  52735. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  52736. */
  52737. this.updateSpeed = 0.01;
  52738. /**
  52739. * The amount of time the particle system is running (depends of the overall update speed).
  52740. */
  52741. this.targetStopDuration = 0;
  52742. /**
  52743. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  52744. */
  52745. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  52746. /**
  52747. * Minimum life time of emitting particles.
  52748. */
  52749. this.minLifeTime = 1;
  52750. /**
  52751. * Maximum life time of emitting particles.
  52752. */
  52753. this.maxLifeTime = 1;
  52754. /**
  52755. * Minimum Size of emitting particles.
  52756. */
  52757. this.minSize = 1;
  52758. /**
  52759. * Maximum Size of emitting particles.
  52760. */
  52761. this.maxSize = 1;
  52762. /**
  52763. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  52764. */
  52765. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52766. /**
  52767. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  52768. */
  52769. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52770. /**
  52771. * Color the particle will have at the end of its lifetime.
  52772. */
  52773. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  52774. /**
  52775. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  52776. */
  52777. this.emitRate = 100;
  52778. /**
  52779. * You can use gravity if you want to give an orientation to your particles.
  52780. */
  52781. this.gravity = BABYLON.Vector3.Zero();
  52782. /**
  52783. * Minimum power of emitting particles.
  52784. */
  52785. this.minEmitPower = 1;
  52786. /**
  52787. * Maximum power of emitting particles.
  52788. */
  52789. this.maxEmitPower = 1;
  52790. /**
  52791. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  52792. * to override the particles.
  52793. */
  52794. this.forceDepthWrite = false;
  52795. this.id = name;
  52796. this.name = name;
  52797. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52798. this._engine = this._scene.getEngine();
  52799. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  52800. this._capacity = fullOptions.capacity;
  52801. this._activeCount = fullOptions.capacity;
  52802. this._currentActiveCount = 0;
  52803. this._scene.particleSystems.push(this);
  52804. this._updateEffectOptions = {
  52805. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  52806. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  52807. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  52808. uniformBuffersNames: [],
  52809. samplers: ["randomSampler"],
  52810. defines: "",
  52811. fallbacks: null,
  52812. onCompiled: null,
  52813. onError: null,
  52814. indexParameters: null,
  52815. maxSimultaneousLights: 0,
  52816. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  52817. };
  52818. // Random data
  52819. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  52820. var d = [];
  52821. for (var i = 0; i < maxTextureSize; ++i) {
  52822. d.push(Math.random());
  52823. d.push(Math.random());
  52824. d.push(Math.random());
  52825. d.push(Math.random());
  52826. }
  52827. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA32F, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  52828. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52829. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52830. this._randomTextureSize = maxTextureSize;
  52831. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  52832. }
  52833. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  52834. /**
  52835. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  52836. */
  52837. get: function () {
  52838. if (!BABYLON.Engine.LastCreatedEngine) {
  52839. return false;
  52840. }
  52841. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  52842. },
  52843. enumerable: true,
  52844. configurable: true
  52845. });
  52846. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  52847. /**
  52848. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52849. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52850. */
  52851. get: function () {
  52852. if (this.particleEmitterType.direction1) {
  52853. return this.particleEmitterType.direction1;
  52854. }
  52855. return BABYLON.Vector3.Zero();
  52856. },
  52857. set: function (value) {
  52858. if (this.particleEmitterType.direction1) {
  52859. this.particleEmitterType.direction1 = value;
  52860. }
  52861. },
  52862. enumerable: true,
  52863. configurable: true
  52864. });
  52865. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  52866. /**
  52867. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52868. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52869. */
  52870. get: function () {
  52871. if (this.particleEmitterType.direction2) {
  52872. return this.particleEmitterType.direction2;
  52873. }
  52874. return BABYLON.Vector3.Zero();
  52875. },
  52876. set: function (value) {
  52877. if (this.particleEmitterType.direction2) {
  52878. this.particleEmitterType.direction2 = value;
  52879. }
  52880. },
  52881. enumerable: true,
  52882. configurable: true
  52883. });
  52884. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  52885. /**
  52886. * 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.
  52887. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52888. */
  52889. get: function () {
  52890. if (this.particleEmitterType.minEmitBox) {
  52891. return this.particleEmitterType.minEmitBox;
  52892. }
  52893. return BABYLON.Vector3.Zero();
  52894. },
  52895. set: function (value) {
  52896. if (this.particleEmitterType.minEmitBox) {
  52897. this.particleEmitterType.minEmitBox = value;
  52898. }
  52899. },
  52900. enumerable: true,
  52901. configurable: true
  52902. });
  52903. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  52904. /**
  52905. * 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.
  52906. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52907. */
  52908. get: function () {
  52909. if (this.particleEmitterType.maxEmitBox) {
  52910. return this.particleEmitterType.maxEmitBox;
  52911. }
  52912. return BABYLON.Vector3.Zero();
  52913. },
  52914. set: function (value) {
  52915. if (this.particleEmitterType.maxEmitBox) {
  52916. this.particleEmitterType.maxEmitBox = value;
  52917. }
  52918. },
  52919. enumerable: true,
  52920. configurable: true
  52921. });
  52922. /**
  52923. * Gets the maximum number of particles active at the same time.
  52924. * @returns The max number of active particles.
  52925. */
  52926. GPUParticleSystem.prototype.getCapacity = function () {
  52927. return this._capacity;
  52928. };
  52929. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  52930. /**
  52931. * Gets or set the number of active particles
  52932. */
  52933. get: function () {
  52934. return this._activeCount;
  52935. },
  52936. set: function (value) {
  52937. this._activeCount = Math.min(value, this._capacity);
  52938. },
  52939. enumerable: true,
  52940. configurable: true
  52941. });
  52942. /**
  52943. * Is this system ready to be used/rendered
  52944. * @return true if the system is ready
  52945. */
  52946. GPUParticleSystem.prototype.isReady = function () {
  52947. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  52948. return false;
  52949. }
  52950. return true;
  52951. };
  52952. /**
  52953. * Gets Wether the system has been started.
  52954. * @returns True if it has been started, otherwise false.
  52955. */
  52956. GPUParticleSystem.prototype.isStarted = function () {
  52957. return this._started;
  52958. };
  52959. /**
  52960. * Starts the particle system and begins to emit.
  52961. */
  52962. GPUParticleSystem.prototype.start = function () {
  52963. this._started = true;
  52964. this._stopped = false;
  52965. };
  52966. /**
  52967. * Stops the particle system.
  52968. */
  52969. GPUParticleSystem.prototype.stop = function () {
  52970. this._stopped = true;
  52971. };
  52972. /**
  52973. * Remove all active particles
  52974. */
  52975. GPUParticleSystem.prototype.reset = function () {
  52976. this._releaseBuffers();
  52977. this._releaseVAOs();
  52978. this._currentActiveCount = 0;
  52979. this._targetIndex = 0;
  52980. };
  52981. /**
  52982. * Returns the string "GPUParticleSystem"
  52983. * @returns a string containing the class name
  52984. */
  52985. GPUParticleSystem.prototype.getClassName = function () {
  52986. return "GPUParticleSystem";
  52987. };
  52988. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  52989. var updateVertexBuffers = {};
  52990. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  52991. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  52992. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  52993. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  52994. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  52995. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  52996. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  52997. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  52998. this._engine.bindArrayBuffer(null);
  52999. return vao;
  53000. };
  53001. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  53002. var renderVertexBuffers = {};
  53003. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  53004. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  53005. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  53006. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  53007. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  53008. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  53009. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  53010. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  53011. this._engine.bindArrayBuffer(null);
  53012. return vao;
  53013. };
  53014. GPUParticleSystem.prototype._initialize = function (force) {
  53015. if (force === void 0) { force = false; }
  53016. if (this._buffer0 && !force) {
  53017. return;
  53018. }
  53019. var engine = this._scene.getEngine();
  53020. var data = new Array();
  53021. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  53022. // position
  53023. data.push(0.0);
  53024. data.push(0.0);
  53025. data.push(0.0);
  53026. // Age and life
  53027. data.push(0.0); // create the particle as a dead one to create a new one at start
  53028. data.push(0.0);
  53029. // Seed
  53030. data.push(Math.random());
  53031. // Size
  53032. data.push(0.0);
  53033. // color
  53034. data.push(0.0);
  53035. data.push(0.0);
  53036. data.push(0.0);
  53037. data.push(0.0);
  53038. // direction
  53039. data.push(0.0);
  53040. data.push(0.0);
  53041. data.push(0.0);
  53042. }
  53043. // Sprite data
  53044. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  53045. -0.5, 0.5, 0, 1,
  53046. -0.5, -0.5, 0, 0,
  53047. 0.5, -0.5, 1, 0]);
  53048. // Buffers
  53049. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  53050. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  53051. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  53052. // Update VAO
  53053. this._updateVAO = [];
  53054. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  53055. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  53056. // Render VAO
  53057. this._renderVAO = [];
  53058. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  53059. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  53060. // Links
  53061. this._sourceBuffer = this._buffer0;
  53062. this._targetBuffer = this._buffer1;
  53063. };
  53064. /** @ignore */
  53065. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  53066. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  53067. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  53068. return;
  53069. }
  53070. this._updateEffectOptions.defines = defines;
  53071. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  53072. };
  53073. /** @ignore */
  53074. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  53075. var defines = "";
  53076. if (this._scene.clipPlane) {
  53077. defines = "\n#define CLIPPLANE";
  53078. }
  53079. if (this._renderEffect && this._renderEffect.defines === defines) {
  53080. return;
  53081. }
  53082. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  53083. };
  53084. /**
  53085. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  53086. */
  53087. GPUParticleSystem.prototype.animate = function () {
  53088. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  53089. this._actualFrame += this._timeDelta;
  53090. if (!this._stopped) {
  53091. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  53092. this.stop();
  53093. }
  53094. }
  53095. };
  53096. /**
  53097. * Renders the particle system in its current state.
  53098. * @returns the current number of particles
  53099. */
  53100. GPUParticleSystem.prototype.render = function () {
  53101. if (!this._started) {
  53102. return 0;
  53103. }
  53104. this._recreateUpdateEffect();
  53105. this._recreateRenderEffect();
  53106. if (!this.isReady()) {
  53107. return 0;
  53108. }
  53109. if (this._currentRenderId === this._scene.getRenderId()) {
  53110. return 0;
  53111. }
  53112. this._currentRenderId = this._scene.getRenderId();
  53113. // Get everything ready to render
  53114. this._initialize();
  53115. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  53116. // Enable update effect
  53117. this._engine.enableEffect(this._updateEffect);
  53118. this._engine.setState(false);
  53119. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  53120. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  53121. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  53122. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  53123. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  53124. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  53125. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  53126. this._updateEffect.setDirectColor4("color1", this.color1);
  53127. this._updateEffect.setDirectColor4("color2", this.color2);
  53128. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  53129. this._updateEffect.setVector3("gravity", this.gravity);
  53130. if (this.particleEmitterType) {
  53131. this.particleEmitterType.applyToShader(this._updateEffect);
  53132. }
  53133. var emitterWM;
  53134. if (this.emitter.position) {
  53135. var emitterMesh = this.emitter;
  53136. emitterWM = emitterMesh.getWorldMatrix();
  53137. }
  53138. else {
  53139. var emitterPosition = this.emitter;
  53140. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  53141. }
  53142. this._updateEffect.setMatrix("emitterWM", emitterWM);
  53143. // Bind source VAO
  53144. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  53145. // Update
  53146. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  53147. this._engine.setRasterizerState(false);
  53148. this._engine.beginTransformFeedback();
  53149. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  53150. this._engine.endTransformFeedback();
  53151. this._engine.setRasterizerState(true);
  53152. this._engine.bindTransformFeedbackBuffer(null);
  53153. // Enable render effect
  53154. this._engine.enableEffect(this._renderEffect);
  53155. var viewMatrix = this._scene.getViewMatrix();
  53156. this._renderEffect.setMatrix("view", viewMatrix);
  53157. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  53158. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  53159. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  53160. if (this._scene.clipPlane) {
  53161. var clipPlane = this._scene.clipPlane;
  53162. var invView = viewMatrix.clone();
  53163. invView.invert();
  53164. this._renderEffect.setMatrix("invView", invView);
  53165. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  53166. }
  53167. // Draw order
  53168. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  53169. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  53170. }
  53171. else {
  53172. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53173. }
  53174. if (this.forceDepthWrite) {
  53175. this._engine.setDepthWrite(true);
  53176. }
  53177. // Bind source VAO
  53178. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  53179. // Render
  53180. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  53181. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53182. // Switch VAOs
  53183. this._targetIndex++;
  53184. if (this._targetIndex === 2) {
  53185. this._targetIndex = 0;
  53186. }
  53187. // Switch buffers
  53188. var tmpBuffer = this._sourceBuffer;
  53189. this._sourceBuffer = this._targetBuffer;
  53190. this._targetBuffer = tmpBuffer;
  53191. return this._currentActiveCount;
  53192. };
  53193. /**
  53194. * Rebuilds the particle system
  53195. */
  53196. GPUParticleSystem.prototype.rebuild = function () {
  53197. this._initialize(true);
  53198. };
  53199. GPUParticleSystem.prototype._releaseBuffers = function () {
  53200. if (this._buffer0) {
  53201. this._buffer0.dispose();
  53202. this._buffer0 = null;
  53203. }
  53204. if (this._buffer1) {
  53205. this._buffer1.dispose();
  53206. this._buffer1 = null;
  53207. }
  53208. if (this._spriteBuffer) {
  53209. this._spriteBuffer.dispose();
  53210. this._spriteBuffer = null;
  53211. }
  53212. };
  53213. GPUParticleSystem.prototype._releaseVAOs = function () {
  53214. if (!this._updateVAO) {
  53215. return;
  53216. }
  53217. for (var index = 0; index < this._updateVAO.length; index++) {
  53218. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  53219. }
  53220. this._updateVAO = [];
  53221. for (var index = 0; index < this._renderVAO.length; index++) {
  53222. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  53223. }
  53224. this._renderVAO = [];
  53225. };
  53226. /**
  53227. * Disposes the particle system and free the associated resources
  53228. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  53229. */
  53230. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  53231. if (disposeTexture === void 0) { disposeTexture = true; }
  53232. var index = this._scene.particleSystems.indexOf(this);
  53233. if (index > -1) {
  53234. this._scene.particleSystems.splice(index, 1);
  53235. }
  53236. this._releaseBuffers();
  53237. this._releaseVAOs();
  53238. if (this._randomTexture) {
  53239. this._randomTexture.dispose();
  53240. this._randomTexture = null;
  53241. }
  53242. if (disposeTexture && this.particleTexture) {
  53243. this.particleTexture.dispose();
  53244. this.particleTexture = null;
  53245. }
  53246. // Callback
  53247. this.onDisposeObservable.notifyObservers(this);
  53248. this.onDisposeObservable.clear();
  53249. };
  53250. /**
  53251. * Clones the particle system.
  53252. * @param name The name of the cloned object
  53253. * @param newEmitter The new emitter to use
  53254. * @returns the cloned particle system
  53255. */
  53256. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  53257. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  53258. BABYLON.Tools.DeepCopy(this, result);
  53259. if (newEmitter === undefined) {
  53260. newEmitter = this.emitter;
  53261. }
  53262. result.emitter = newEmitter;
  53263. if (this.particleTexture) {
  53264. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  53265. }
  53266. return result;
  53267. };
  53268. /**
  53269. * Serializes the particle system to a JSON object.
  53270. * @returns the JSON object
  53271. */
  53272. GPUParticleSystem.prototype.serialize = function () {
  53273. var serializationObject = {};
  53274. serializationObject.name = this.name;
  53275. serializationObject.id = this.id;
  53276. // Emitter
  53277. if (this.emitter.position) {
  53278. var emitterMesh = this.emitter;
  53279. serializationObject.emitterId = emitterMesh.id;
  53280. }
  53281. else {
  53282. var emitterPosition = this.emitter;
  53283. serializationObject.emitter = emitterPosition.asArray();
  53284. }
  53285. serializationObject.capacity = this.getCapacity();
  53286. if (this.particleTexture) {
  53287. serializationObject.textureName = this.particleTexture.name;
  53288. }
  53289. // Animations
  53290. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  53291. // Particle system
  53292. serializationObject.activeParticleCount = this.activeParticleCount;
  53293. serializationObject.randomTextureSize = this._randomTextureSize;
  53294. serializationObject.minSize = this.minSize;
  53295. serializationObject.maxSize = this.maxSize;
  53296. serializationObject.minEmitPower = this.minEmitPower;
  53297. serializationObject.maxEmitPower = this.maxEmitPower;
  53298. serializationObject.minLifeTime = this.minLifeTime;
  53299. serializationObject.maxLifeTime = this.maxLifeTime;
  53300. serializationObject.emitRate = this.emitRate;
  53301. serializationObject.gravity = this.gravity.asArray();
  53302. serializationObject.color1 = this.color1.asArray();
  53303. serializationObject.color2 = this.color2.asArray();
  53304. serializationObject.colorDead = this.colorDead.asArray();
  53305. serializationObject.updateSpeed = this.updateSpeed;
  53306. serializationObject.targetStopDuration = this.targetStopDuration;
  53307. serializationObject.blendMode = this.blendMode;
  53308. // Emitter
  53309. if (this.particleEmitterType) {
  53310. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  53311. }
  53312. return serializationObject;
  53313. };
  53314. /**
  53315. * Parses a JSON object to create a GPU particle system.
  53316. * @param parsedParticleSystem The JSON object to parse
  53317. * @param scene The scene to create the particle system in
  53318. * @param rootUrl The root url to use to load external dependencies like texture
  53319. * @returns the parsed GPU particle system
  53320. */
  53321. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  53322. var name = parsedParticleSystem.name;
  53323. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  53324. if (parsedParticleSystem.id) {
  53325. particleSystem.id = parsedParticleSystem.id;
  53326. }
  53327. // Texture
  53328. if (parsedParticleSystem.textureName) {
  53329. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  53330. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  53331. }
  53332. // Emitter
  53333. if (parsedParticleSystem.emitterId) {
  53334. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  53335. }
  53336. else {
  53337. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  53338. }
  53339. // Animations
  53340. if (parsedParticleSystem.animations) {
  53341. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  53342. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  53343. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  53344. }
  53345. }
  53346. // Particle system
  53347. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  53348. particleSystem.minSize = parsedParticleSystem.minSize;
  53349. particleSystem.maxSize = parsedParticleSystem.maxSize;
  53350. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  53351. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  53352. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  53353. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  53354. particleSystem.emitRate = parsedParticleSystem.emitRate;
  53355. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  53356. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  53357. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  53358. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  53359. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  53360. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  53361. particleSystem.blendMode = parsedParticleSystem.blendMode;
  53362. // Emitter
  53363. if (parsedParticleSystem.particleEmitterType) {
  53364. var emitterType = void 0;
  53365. switch (parsedParticleSystem.particleEmitterType.type) {
  53366. case "SphereEmitter":
  53367. emitterType = new BABYLON.SphereParticleEmitter();
  53368. break;
  53369. case "SphereDirectedParticleEmitter":
  53370. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  53371. break;
  53372. case "ConeEmitter":
  53373. emitterType = new BABYLON.ConeParticleEmitter();
  53374. break;
  53375. case "BoxEmitter":
  53376. default:
  53377. emitterType = new BABYLON.BoxParticleEmitter();
  53378. break;
  53379. }
  53380. emitterType.parse(parsedParticleSystem.particleEmitterType);
  53381. particleSystem.particleEmitterType = emitterType;
  53382. }
  53383. return particleSystem;
  53384. };
  53385. return GPUParticleSystem;
  53386. }());
  53387. BABYLON.GPUParticleSystem = GPUParticleSystem;
  53388. })(BABYLON || (BABYLON = {}));
  53389. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  53390. var BABYLON;
  53391. (function (BABYLON) {
  53392. /**
  53393. * Represents one particle of a solid particle system.
  53394. * @see SolidParticleSystem
  53395. */
  53396. var SolidParticle = /** @class */ (function () {
  53397. /**
  53398. * Creates a Solid Particle object.
  53399. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  53400. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  53401. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  53402. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  53403. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  53404. * @param shapeId (integer) is the model shape identifier in the SPS.
  53405. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  53406. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  53407. */
  53408. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  53409. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  53410. /**
  53411. * particle global index
  53412. */
  53413. this.idx = 0;
  53414. /**
  53415. * The color of the particle
  53416. */
  53417. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53418. /**
  53419. * The world space position of the particle.
  53420. */
  53421. this.position = BABYLON.Vector3.Zero();
  53422. /**
  53423. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  53424. */
  53425. this.rotation = BABYLON.Vector3.Zero();
  53426. /**
  53427. * The scaling of the particle.
  53428. */
  53429. this.scaling = BABYLON.Vector3.One();
  53430. /**
  53431. * The uvs of the particle.
  53432. */
  53433. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  53434. /**
  53435. * The current speed of the particle.
  53436. */
  53437. this.velocity = BABYLON.Vector3.Zero();
  53438. /**
  53439. * The pivot point in the particle local space.
  53440. */
  53441. this.pivot = BABYLON.Vector3.Zero();
  53442. /**
  53443. * Must the particle be translated from its pivot point in its local space ?
  53444. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  53445. * Default : false
  53446. */
  53447. this.translateFromPivot = false;
  53448. /**
  53449. * Is the particle active or not ?
  53450. */
  53451. this.alive = true;
  53452. /**
  53453. * Is the particle visible or not ?
  53454. */
  53455. this.isVisible = true;
  53456. /**
  53457. * Index of this particle in the global "positions" array (Internal use)
  53458. */
  53459. this._pos = 0;
  53460. /**
  53461. * Index of this particle in the global "indices" array (Internal use)
  53462. */
  53463. this._ind = 0;
  53464. /**
  53465. * ModelShape id of this particle
  53466. */
  53467. this.shapeId = 0;
  53468. /**
  53469. * Index of the particle in its shape id (Internal use)
  53470. */
  53471. this.idxInShape = 0;
  53472. /**
  53473. * Still set as invisible in order to skip useless computations (Internal use)
  53474. */
  53475. this._stillInvisible = false;
  53476. /**
  53477. * Last computed particle rotation matrix
  53478. */
  53479. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  53480. /**
  53481. * Parent particle Id, if any.
  53482. * Default null.
  53483. */
  53484. this.parentId = null;
  53485. /**
  53486. * Internal global position in the SPS.
  53487. */
  53488. this._globalPosition = BABYLON.Vector3.Zero();
  53489. this.idx = particleIndex;
  53490. this._pos = positionIndex;
  53491. this._ind = indiceIndex;
  53492. this._model = model;
  53493. this.shapeId = shapeId;
  53494. this.idxInShape = idxInShape;
  53495. this._sps = sps;
  53496. if (modelBoundingInfo) {
  53497. this._modelBoundingInfo = modelBoundingInfo;
  53498. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  53499. }
  53500. }
  53501. Object.defineProperty(SolidParticle.prototype, "scale", {
  53502. /**
  53503. * Legacy support, changed scale to scaling
  53504. */
  53505. get: function () {
  53506. return this.scaling;
  53507. },
  53508. /**
  53509. * Legacy support, changed scale to scaling
  53510. */
  53511. set: function (scale) {
  53512. this.scaling = scale;
  53513. },
  53514. enumerable: true,
  53515. configurable: true
  53516. });
  53517. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  53518. /**
  53519. * Legacy support, changed quaternion to rotationQuaternion
  53520. */
  53521. get: function () {
  53522. return this.rotationQuaternion;
  53523. },
  53524. /**
  53525. * Legacy support, changed quaternion to rotationQuaternion
  53526. */
  53527. set: function (q) {
  53528. this.rotationQuaternion = q;
  53529. },
  53530. enumerable: true,
  53531. configurable: true
  53532. });
  53533. /**
  53534. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  53535. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  53536. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  53537. * @returns true if it intersects
  53538. */
  53539. SolidParticle.prototype.intersectsMesh = function (target) {
  53540. if (!this._boundingInfo || !target._boundingInfo) {
  53541. return false;
  53542. }
  53543. if (this._sps._bSphereOnly) {
  53544. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  53545. }
  53546. return this._boundingInfo.intersects(target._boundingInfo, false);
  53547. };
  53548. return SolidParticle;
  53549. }());
  53550. BABYLON.SolidParticle = SolidParticle;
  53551. /**
  53552. * Represents the shape of the model used by one particle of a solid particle system.
  53553. * SPS internal tool, don't use it manually.
  53554. * @see SolidParticleSystem
  53555. */
  53556. var ModelShape = /** @class */ (function () {
  53557. /**
  53558. * 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.
  53559. * SPS internal tool, don't use it manually.
  53560. * @ignore
  53561. */
  53562. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  53563. /**
  53564. * length of the shape in the model indices array (internal use)
  53565. */
  53566. this._indicesLength = 0;
  53567. this.shapeID = id;
  53568. this._shape = shape;
  53569. this._indicesLength = indicesLength;
  53570. this._shapeUV = shapeUV;
  53571. this._positionFunction = posFunction;
  53572. this._vertexFunction = vtxFunction;
  53573. }
  53574. return ModelShape;
  53575. }());
  53576. BABYLON.ModelShape = ModelShape;
  53577. /**
  53578. * Represents a Depth Sorted Particle in the solid particle system.
  53579. * @see SolidParticleSystem
  53580. */
  53581. var DepthSortedParticle = /** @class */ (function () {
  53582. function DepthSortedParticle() {
  53583. /**
  53584. * Index of the particle in the "indices" array
  53585. */
  53586. this.ind = 0;
  53587. /**
  53588. * Length of the particle shape in the "indices" array
  53589. */
  53590. this.indicesLength = 0;
  53591. /**
  53592. * Squared distance from the particle to the camera
  53593. */
  53594. this.sqDistance = 0.0;
  53595. }
  53596. return DepthSortedParticle;
  53597. }());
  53598. BABYLON.DepthSortedParticle = DepthSortedParticle;
  53599. })(BABYLON || (BABYLON = {}));
  53600. //# sourceMappingURL=babylon.solidParticle.js.map
  53601. var BABYLON;
  53602. (function (BABYLON) {
  53603. /**
  53604. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  53605. *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.
  53606. * The SPS is also a particle system. It provides some methods to manage the particles.
  53607. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  53608. *
  53609. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  53610. */
  53611. var SolidParticleSystem = /** @class */ (function () {
  53612. /**
  53613. * Creates a SPS (Solid Particle System) object.
  53614. * @param name (String) is the SPS name, this will be the underlying mesh name.
  53615. * @param scene (Scene) is the scene in which the SPS is added.
  53616. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  53617. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  53618. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  53619. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  53620. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  53621. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  53622. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  53623. */
  53624. function SolidParticleSystem(name, scene, options) {
  53625. /**
  53626. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  53627. * Example : var p = SPS.particles[i];
  53628. */
  53629. this.particles = new Array();
  53630. /**
  53631. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  53632. */
  53633. this.nbParticles = 0;
  53634. /**
  53635. * If the particles must ever face the camera (default false). Useful for planar particles.
  53636. */
  53637. this.billboard = false;
  53638. /**
  53639. * Recompute normals when adding a shape
  53640. */
  53641. this.recomputeNormals = true;
  53642. /**
  53643. * This a counter ofr your own usage. It's not set by any SPS functions.
  53644. */
  53645. this.counter = 0;
  53646. /**
  53647. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  53648. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  53649. */
  53650. this.vars = {};
  53651. /**
  53652. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  53653. */
  53654. this._bSphereOnly = false;
  53655. /**
  53656. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  53657. */
  53658. this._bSphereRadiusFactor = 1.0;
  53659. this._positions = new Array();
  53660. this._indices = new Array();
  53661. this._normals = new Array();
  53662. this._colors = new Array();
  53663. this._uvs = new Array();
  53664. this._index = 0; // indices index
  53665. this._updatable = true;
  53666. this._pickable = false;
  53667. this._isVisibilityBoxLocked = false;
  53668. this._alwaysVisible = false;
  53669. this._depthSort = false;
  53670. this._shapeCounter = 0;
  53671. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  53672. this._color = new BABYLON.Color4(0, 0, 0, 0);
  53673. this._computeParticleColor = true;
  53674. this._computeParticleTexture = true;
  53675. this._computeParticleRotation = true;
  53676. this._computeParticleVertex = false;
  53677. this._computeBoundingBox = false;
  53678. this._depthSortParticles = true;
  53679. this._cam_axisZ = BABYLON.Vector3.Zero();
  53680. this._cam_axisY = BABYLON.Vector3.Zero();
  53681. this._cam_axisX = BABYLON.Vector3.Zero();
  53682. this._axisZ = BABYLON.Axis.Z;
  53683. this._camDir = BABYLON.Vector3.Zero();
  53684. this._camInvertedPosition = BABYLON.Vector3.Zero();
  53685. this._rotMatrix = new BABYLON.Matrix();
  53686. this._invertMatrix = new BABYLON.Matrix();
  53687. this._rotated = BABYLON.Vector3.Zero();
  53688. this._quaternion = new BABYLON.Quaternion();
  53689. this._vertex = BABYLON.Vector3.Zero();
  53690. this._normal = BABYLON.Vector3.Zero();
  53691. this._yaw = 0.0;
  53692. this._pitch = 0.0;
  53693. this._roll = 0.0;
  53694. this._halfroll = 0.0;
  53695. this._halfpitch = 0.0;
  53696. this._halfyaw = 0.0;
  53697. this._sinRoll = 0.0;
  53698. this._cosRoll = 0.0;
  53699. this._sinPitch = 0.0;
  53700. this._cosPitch = 0.0;
  53701. this._sinYaw = 0.0;
  53702. this._cosYaw = 0.0;
  53703. this._mustUnrotateFixedNormals = false;
  53704. this._minimum = BABYLON.Vector3.Zero();
  53705. this._maximum = BABYLON.Vector3.Zero();
  53706. this._minBbox = BABYLON.Vector3.Zero();
  53707. this._maxBbox = BABYLON.Vector3.Zero();
  53708. this._particlesIntersect = false;
  53709. this._depthSortFunction = function (p1, p2) {
  53710. return (p2.sqDistance - p1.sqDistance);
  53711. };
  53712. this._needs32Bits = false;
  53713. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  53714. this._scaledPivot = BABYLON.Vector3.Zero();
  53715. this._particleHasParent = false;
  53716. this.name = name;
  53717. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53718. this._camera = scene.activeCamera;
  53719. this._pickable = options ? options.isPickable : false;
  53720. this._depthSort = options ? options.enableDepthSort : false;
  53721. this._particlesIntersect = options ? options.particleIntersection : false;
  53722. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  53723. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  53724. if (options && options.updatable) {
  53725. this._updatable = options.updatable;
  53726. }
  53727. else {
  53728. this._updatable = true;
  53729. }
  53730. if (this._pickable) {
  53731. this.pickedParticles = [];
  53732. }
  53733. if (this._depthSort) {
  53734. this.depthSortedParticles = [];
  53735. }
  53736. }
  53737. /**
  53738. * Builds the SPS underlying mesh. Returns a standard Mesh.
  53739. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  53740. * @returns the created mesh
  53741. */
  53742. SolidParticleSystem.prototype.buildMesh = function () {
  53743. if (this.nbParticles === 0) {
  53744. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  53745. this.addShape(triangle, 1);
  53746. triangle.dispose();
  53747. }
  53748. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  53749. this._positions32 = new Float32Array(this._positions);
  53750. this._uvs32 = new Float32Array(this._uvs);
  53751. this._colors32 = new Float32Array(this._colors);
  53752. if (this.recomputeNormals) {
  53753. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  53754. }
  53755. this._normals32 = new Float32Array(this._normals);
  53756. this._fixedNormal32 = new Float32Array(this._normals);
  53757. if (this._mustUnrotateFixedNormals) {
  53758. this._unrotateFixedNormals();
  53759. }
  53760. var vertexData = new BABYLON.VertexData();
  53761. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  53762. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  53763. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  53764. if (this._uvs32) {
  53765. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  53766. ;
  53767. }
  53768. if (this._colors32) {
  53769. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  53770. }
  53771. var mesh = new BABYLON.Mesh(this.name, this._scene);
  53772. vertexData.applyToMesh(mesh, this._updatable);
  53773. this.mesh = mesh;
  53774. this.mesh.isPickable = this._pickable;
  53775. // free memory
  53776. if (!this._depthSort) {
  53777. this._indices = null;
  53778. }
  53779. this._positions = null;
  53780. this._normals = null;
  53781. this._uvs = null;
  53782. this._colors = null;
  53783. if (!this._updatable) {
  53784. this.particles.length = 0;
  53785. }
  53786. return mesh;
  53787. };
  53788. /**
  53789. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  53790. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  53791. * Thus the particles generated from `digest()` have their property `position` set yet.
  53792. * @param mesh ( Mesh ) is the mesh to be digested
  53793. * @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
  53794. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  53795. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  53796. * @returns the current SPS
  53797. */
  53798. SolidParticleSystem.prototype.digest = function (mesh, options) {
  53799. var size = (options && options.facetNb) || 1;
  53800. var number = (options && options.number) || 0;
  53801. var delta = (options && options.delta) || 0;
  53802. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53803. var meshInd = mesh.getIndices();
  53804. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53805. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53806. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53807. var f = 0; // facet counter
  53808. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  53809. // compute size from number
  53810. if (number) {
  53811. number = (number > totalFacets) ? totalFacets : number;
  53812. size = Math.round(totalFacets / number);
  53813. delta = 0;
  53814. }
  53815. else {
  53816. size = (size > totalFacets) ? totalFacets : size;
  53817. }
  53818. var facetPos = []; // submesh positions
  53819. var facetInd = []; // submesh indices
  53820. var facetUV = []; // submesh UV
  53821. var facetCol = []; // submesh colors
  53822. var barycenter = BABYLON.Vector3.Zero();
  53823. var sizeO = size;
  53824. while (f < totalFacets) {
  53825. size = sizeO + Math.floor((1 + delta) * Math.random());
  53826. if (f > totalFacets - size) {
  53827. size = totalFacets - f;
  53828. }
  53829. // reset temp arrays
  53830. facetPos.length = 0;
  53831. facetInd.length = 0;
  53832. facetUV.length = 0;
  53833. facetCol.length = 0;
  53834. // iterate over "size" facets
  53835. var fi = 0;
  53836. for (var j = f * 3; j < (f + size) * 3; j++) {
  53837. facetInd.push(fi);
  53838. var i = meshInd[j];
  53839. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  53840. if (meshUV) {
  53841. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  53842. }
  53843. if (meshCol) {
  53844. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  53845. }
  53846. fi++;
  53847. }
  53848. // create a model shape for each single particle
  53849. var idx = this.nbParticles;
  53850. var shape = this._posToShape(facetPos);
  53851. var shapeUV = this._uvsToShapeUV(facetUV);
  53852. // compute the barycenter of the shape
  53853. var v;
  53854. for (v = 0; v < shape.length; v++) {
  53855. barycenter.addInPlace(shape[v]);
  53856. }
  53857. barycenter.scaleInPlace(1 / shape.length);
  53858. // shift the shape from its barycenter to the origin
  53859. for (v = 0; v < shape.length; v++) {
  53860. shape[v].subtractInPlace(barycenter);
  53861. }
  53862. var bInfo;
  53863. if (this._particlesIntersect) {
  53864. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  53865. }
  53866. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  53867. // add the particle in the SPS
  53868. var currentPos = this._positions.length;
  53869. var currentInd = this._indices.length;
  53870. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  53871. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  53872. // initialize the particle position
  53873. this.particles[this.nbParticles].position.addInPlace(barycenter);
  53874. this._index += shape.length;
  53875. idx++;
  53876. this.nbParticles++;
  53877. this._shapeCounter++;
  53878. f += size;
  53879. }
  53880. return this;
  53881. };
  53882. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  53883. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  53884. var index = 0;
  53885. var idx = 0;
  53886. for (var p = 0; p < this.particles.length; p++) {
  53887. this._particle = this.particles[p];
  53888. this._shape = this._particle._model._shape;
  53889. if (this._particle.rotationQuaternion) {
  53890. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53891. }
  53892. else {
  53893. this._yaw = this._particle.rotation.y;
  53894. this._pitch = this._particle.rotation.x;
  53895. this._roll = this._particle.rotation.z;
  53896. this._quaternionRotationYPR();
  53897. }
  53898. this._quaternionToRotationMatrix();
  53899. this._rotMatrix.invertToRef(this._invertMatrix);
  53900. for (var pt = 0; pt < this._shape.length; pt++) {
  53901. idx = index + pt * 3;
  53902. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  53903. this._fixedNormal32[idx] = this._normal.x;
  53904. this._fixedNormal32[idx + 1] = this._normal.y;
  53905. this._fixedNormal32[idx + 2] = this._normal.z;
  53906. }
  53907. index = idx + 3;
  53908. }
  53909. };
  53910. //reset copy
  53911. SolidParticleSystem.prototype._resetCopy = function () {
  53912. this._copy.position.x = 0;
  53913. this._copy.position.y = 0;
  53914. this._copy.position.z = 0;
  53915. this._copy.rotation.x = 0;
  53916. this._copy.rotation.y = 0;
  53917. this._copy.rotation.z = 0;
  53918. this._copy.rotationQuaternion = null;
  53919. this._copy.scaling.x = 1.0;
  53920. this._copy.scaling.y = 1.0;
  53921. this._copy.scaling.z = 1.0;
  53922. this._copy.uvs.x = 0;
  53923. this._copy.uvs.y = 0;
  53924. this._copy.uvs.z = 1.0;
  53925. this._copy.uvs.w = 1.0;
  53926. this._copy.color = null;
  53927. this._copy.translateFromPivot = false;
  53928. };
  53929. // _meshBuilder : inserts the shape model in the global SPS mesh
  53930. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  53931. var i;
  53932. var u = 0;
  53933. var c = 0;
  53934. var n = 0;
  53935. this._resetCopy();
  53936. if (options && options.positionFunction) {
  53937. options.positionFunction(this._copy, idx, idxInShape);
  53938. this._mustUnrotateFixedNormals = true;
  53939. }
  53940. if (this._copy.rotationQuaternion) {
  53941. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  53942. }
  53943. else {
  53944. this._yaw = this._copy.rotation.y;
  53945. this._pitch = this._copy.rotation.x;
  53946. this._roll = this._copy.rotation.z;
  53947. this._quaternionRotationYPR();
  53948. }
  53949. this._quaternionToRotationMatrix();
  53950. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  53951. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  53952. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  53953. if (this._copy.translateFromPivot) {
  53954. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  53955. }
  53956. else {
  53957. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  53958. }
  53959. for (i = 0; i < shape.length; i++) {
  53960. this._vertex.x = shape[i].x;
  53961. this._vertex.y = shape[i].y;
  53962. this._vertex.z = shape[i].z;
  53963. if (options && options.vertexFunction) {
  53964. options.vertexFunction(this._copy, this._vertex, i);
  53965. }
  53966. this._vertex.x *= this._copy.scaling.x;
  53967. this._vertex.y *= this._copy.scaling.y;
  53968. this._vertex.z *= this._copy.scaling.z;
  53969. this._vertex.x -= this._scaledPivot.x;
  53970. this._vertex.y -= this._scaledPivot.y;
  53971. this._vertex.z -= this._scaledPivot.z;
  53972. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  53973. this._rotated.addInPlace(this._pivotBackTranslation);
  53974. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  53975. if (meshUV) {
  53976. 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);
  53977. u += 2;
  53978. }
  53979. if (this._copy.color) {
  53980. this._color = this._copy.color;
  53981. }
  53982. else if (meshCol && meshCol[c] !== undefined) {
  53983. this._color.r = meshCol[c];
  53984. this._color.g = meshCol[c + 1];
  53985. this._color.b = meshCol[c + 2];
  53986. this._color.a = meshCol[c + 3];
  53987. }
  53988. else {
  53989. this._color.r = 1.0;
  53990. this._color.g = 1.0;
  53991. this._color.b = 1.0;
  53992. this._color.a = 1.0;
  53993. }
  53994. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  53995. c += 4;
  53996. if (!this.recomputeNormals && meshNor) {
  53997. this._normal.x = meshNor[n];
  53998. this._normal.y = meshNor[n + 1];
  53999. this._normal.z = meshNor[n + 2];
  54000. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  54001. normals.push(this._normal.x, this._normal.y, this._normal.z);
  54002. n += 3;
  54003. }
  54004. }
  54005. for (i = 0; i < meshInd.length; i++) {
  54006. var current_ind = p + meshInd[i];
  54007. indices.push(current_ind);
  54008. if (current_ind > 65535) {
  54009. this._needs32Bits = true;
  54010. }
  54011. }
  54012. if (this._pickable) {
  54013. var nbfaces = meshInd.length / 3;
  54014. for (i = 0; i < nbfaces; i++) {
  54015. this.pickedParticles.push({ idx: idx, faceId: i });
  54016. }
  54017. }
  54018. if (this._depthSort) {
  54019. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  54020. }
  54021. return this._copy;
  54022. };
  54023. // returns a shape array from positions array
  54024. SolidParticleSystem.prototype._posToShape = function (positions) {
  54025. var shape = [];
  54026. for (var i = 0; i < positions.length; i += 3) {
  54027. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  54028. }
  54029. return shape;
  54030. };
  54031. // returns a shapeUV array from a Vector4 uvs
  54032. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  54033. var shapeUV = [];
  54034. if (uvs) {
  54035. for (var i = 0; i < uvs.length; i++)
  54036. shapeUV.push(uvs[i]);
  54037. }
  54038. return shapeUV;
  54039. };
  54040. // adds a new particle object in the particles array
  54041. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  54042. if (bInfo === void 0) { bInfo = null; }
  54043. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  54044. this.particles.push(sp);
  54045. return sp;
  54046. };
  54047. /**
  54048. * Adds some particles to the SPS from the model shape. Returns the shape id.
  54049. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  54050. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  54051. * @param nb (positive integer) the number of particles to be created from this model
  54052. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  54053. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  54054. * @returns the number of shapes in the system
  54055. */
  54056. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  54057. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54058. var meshInd = mesh.getIndices();
  54059. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54060. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54061. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54062. var bbInfo;
  54063. if (this._particlesIntersect) {
  54064. bbInfo = mesh.getBoundingInfo();
  54065. }
  54066. var shape = this._posToShape(meshPos);
  54067. var shapeUV = this._uvsToShapeUV(meshUV);
  54068. var posfunc = options ? options.positionFunction : null;
  54069. var vtxfunc = options ? options.vertexFunction : null;
  54070. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  54071. // particles
  54072. var sp;
  54073. var currentCopy;
  54074. var idx = this.nbParticles;
  54075. for (var i = 0; i < nb; i++) {
  54076. var currentPos = this._positions.length;
  54077. var currentInd = this._indices.length;
  54078. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  54079. if (this._updatable) {
  54080. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  54081. sp.position.copyFrom(currentCopy.position);
  54082. sp.rotation.copyFrom(currentCopy.rotation);
  54083. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  54084. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  54085. }
  54086. if (currentCopy.color && sp.color) {
  54087. sp.color.copyFrom(currentCopy.color);
  54088. }
  54089. sp.scaling.copyFrom(currentCopy.scaling);
  54090. sp.uvs.copyFrom(currentCopy.uvs);
  54091. }
  54092. this._index += shape.length;
  54093. idx++;
  54094. }
  54095. this.nbParticles += nb;
  54096. this._shapeCounter++;
  54097. return this._shapeCounter - 1;
  54098. };
  54099. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  54100. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  54101. this._resetCopy();
  54102. if (particle._model._positionFunction) {
  54103. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  54104. }
  54105. if (this._copy.rotationQuaternion) {
  54106. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54107. }
  54108. else {
  54109. this._yaw = this._copy.rotation.y;
  54110. this._pitch = this._copy.rotation.x;
  54111. this._roll = this._copy.rotation.z;
  54112. this._quaternionRotationYPR();
  54113. }
  54114. this._quaternionToRotationMatrix();
  54115. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  54116. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  54117. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  54118. if (this._copy.translateFromPivot) {
  54119. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  54120. }
  54121. else {
  54122. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  54123. }
  54124. this._shape = particle._model._shape;
  54125. for (var pt = 0; pt < this._shape.length; pt++) {
  54126. this._vertex.x = this._shape[pt].x;
  54127. this._vertex.y = this._shape[pt].y;
  54128. this._vertex.z = this._shape[pt].z;
  54129. if (particle._model._vertexFunction) {
  54130. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  54131. }
  54132. this._vertex.x *= this._copy.scaling.x;
  54133. this._vertex.y *= this._copy.scaling.y;
  54134. this._vertex.z *= this._copy.scaling.z;
  54135. this._vertex.x -= this._scaledPivot.x;
  54136. this._vertex.y -= this._scaledPivot.y;
  54137. this._vertex.z -= this._scaledPivot.z;
  54138. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54139. this._rotated.addInPlace(this._pivotBackTranslation);
  54140. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  54141. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  54142. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  54143. }
  54144. particle.position.x = 0.0;
  54145. particle.position.y = 0.0;
  54146. particle.position.z = 0.0;
  54147. particle.rotation.x = 0.0;
  54148. particle.rotation.y = 0.0;
  54149. particle.rotation.z = 0.0;
  54150. particle.rotationQuaternion = null;
  54151. particle.scaling.x = 1.0;
  54152. particle.scaling.y = 1.0;
  54153. particle.scaling.z = 1.0;
  54154. particle.uvs.x = 0.0;
  54155. particle.uvs.y = 0.0;
  54156. particle.uvs.z = 1.0;
  54157. particle.uvs.w = 1.0;
  54158. particle.pivot.x = 0.0;
  54159. particle.pivot.y = 0.0;
  54160. particle.pivot.z = 0.0;
  54161. particle.translateFromPivot = false;
  54162. particle.parentId = null;
  54163. };
  54164. /**
  54165. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  54166. * @returns the SPS.
  54167. */
  54168. SolidParticleSystem.prototype.rebuildMesh = function () {
  54169. for (var p = 0; p < this.particles.length; p++) {
  54170. this._rebuildParticle(this.particles[p]);
  54171. }
  54172. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54173. return this;
  54174. };
  54175. /**
  54176. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  54177. * This method calls `updateParticle()` for each particle of the SPS.
  54178. * For an animated SPS, it is usually called within the render loop.
  54179. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  54180. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  54181. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  54182. * @returns the SPS.
  54183. */
  54184. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  54185. if (start === void 0) { start = 0; }
  54186. if (end === void 0) { end = this.nbParticles - 1; }
  54187. if (update === void 0) { update = true; }
  54188. if (!this._updatable) {
  54189. return this;
  54190. }
  54191. // custom beforeUpdate
  54192. this.beforeUpdateParticles(start, end, update);
  54193. this._cam_axisX.x = 1.0;
  54194. this._cam_axisX.y = 0.0;
  54195. this._cam_axisX.z = 0.0;
  54196. this._cam_axisY.x = 0.0;
  54197. this._cam_axisY.y = 1.0;
  54198. this._cam_axisY.z = 0.0;
  54199. this._cam_axisZ.x = 0.0;
  54200. this._cam_axisZ.y = 0.0;
  54201. this._cam_axisZ.z = 1.0;
  54202. // cases when the World Matrix is to be computed first
  54203. if (this.billboard || this._depthSort) {
  54204. this.mesh.computeWorldMatrix(true);
  54205. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  54206. }
  54207. // if the particles will always face the camera
  54208. if (this.billboard) {
  54209. // compute the camera position and un-rotate it by the current mesh rotation
  54210. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  54211. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  54212. this._cam_axisZ.normalize();
  54213. // same for camera up vector extracted from the cam view matrix
  54214. var view = this._camera.getViewMatrix(true);
  54215. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  54216. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  54217. this._cam_axisY.normalize();
  54218. this._cam_axisX.normalize();
  54219. }
  54220. // if depthSort, compute the camera global position in the mesh local system
  54221. if (this._depthSort) {
  54222. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  54223. }
  54224. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  54225. var idx = 0; // current position index in the global array positions32
  54226. var index = 0; // position start index in the global array positions32 of the current particle
  54227. var colidx = 0; // current color index in the global array colors32
  54228. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  54229. var uvidx = 0; // current uv index in the global array uvs32
  54230. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  54231. var pt = 0; // current index in the particle model shape
  54232. if (this.mesh.isFacetDataEnabled) {
  54233. this._computeBoundingBox = true;
  54234. }
  54235. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  54236. if (this._computeBoundingBox) {
  54237. if (start == 0 && end == this.nbParticles - 1) {
  54238. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  54239. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  54240. }
  54241. else {
  54242. if (this.mesh._boundingInfo) {
  54243. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  54244. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  54245. }
  54246. }
  54247. }
  54248. // particle loop
  54249. index = this.particles[start]._pos;
  54250. var vpos = (index / 3) | 0;
  54251. colorIndex = vpos * 4;
  54252. uvIndex = vpos * 2;
  54253. for (var p = start; p <= end; p++) {
  54254. this._particle = this.particles[p];
  54255. this._shape = this._particle._model._shape;
  54256. this._shapeUV = this._particle._model._shapeUV;
  54257. // call to custom user function to update the particle properties
  54258. this.updateParticle(this._particle);
  54259. // camera-particle distance for depth sorting
  54260. if (this._depthSort && this._depthSortParticles) {
  54261. var dsp = this.depthSortedParticles[p];
  54262. dsp.ind = this._particle._ind;
  54263. dsp.indicesLength = this._particle._model._indicesLength;
  54264. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  54265. }
  54266. // skip the computations for inactive or already invisible particles
  54267. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  54268. // increment indexes for the next particle
  54269. pt = this._shape.length;
  54270. index += pt * 3;
  54271. colorIndex += pt * 4;
  54272. uvIndex += pt * 2;
  54273. continue;
  54274. }
  54275. if (this._particle.isVisible) {
  54276. this._particle._stillInvisible = false; // un-mark permanent invisibility
  54277. this._particleHasParent = (this._particle.parentId !== null);
  54278. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  54279. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  54280. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  54281. // particle rotation matrix
  54282. if (this.billboard) {
  54283. this._particle.rotation.x = 0.0;
  54284. this._particle.rotation.y = 0.0;
  54285. }
  54286. if (this._computeParticleRotation || this.billboard) {
  54287. if (this._particle.rotationQuaternion) {
  54288. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54289. }
  54290. else {
  54291. this._yaw = this._particle.rotation.y;
  54292. this._pitch = this._particle.rotation.x;
  54293. this._roll = this._particle.rotation.z;
  54294. this._quaternionRotationYPR();
  54295. }
  54296. this._quaternionToRotationMatrix();
  54297. }
  54298. if (this._particleHasParent) {
  54299. this._parent = this.particles[this._particle.parentId];
  54300. 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];
  54301. 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];
  54302. 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];
  54303. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  54304. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  54305. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  54306. if (this._computeParticleRotation || this.billboard) {
  54307. 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];
  54308. 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];
  54309. 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];
  54310. 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];
  54311. 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];
  54312. 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];
  54313. 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];
  54314. 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];
  54315. 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];
  54316. }
  54317. }
  54318. else {
  54319. this._particle._globalPosition.x = this._particle.position.x;
  54320. this._particle._globalPosition.y = this._particle.position.y;
  54321. this._particle._globalPosition.z = this._particle.position.z;
  54322. if (this._computeParticleRotation || this.billboard) {
  54323. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  54324. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  54325. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  54326. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  54327. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  54328. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  54329. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  54330. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  54331. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  54332. }
  54333. }
  54334. if (this._particle.translateFromPivot) {
  54335. this._pivotBackTranslation.x = 0.0;
  54336. this._pivotBackTranslation.y = 0.0;
  54337. this._pivotBackTranslation.z = 0.0;
  54338. }
  54339. else {
  54340. this._pivotBackTranslation.x = this._scaledPivot.x;
  54341. this._pivotBackTranslation.y = this._scaledPivot.y;
  54342. this._pivotBackTranslation.z = this._scaledPivot.z;
  54343. }
  54344. // particle vertex loop
  54345. for (pt = 0; pt < this._shape.length; pt++) {
  54346. idx = index + pt * 3;
  54347. colidx = colorIndex + pt * 4;
  54348. uvidx = uvIndex + pt * 2;
  54349. this._vertex.x = this._shape[pt].x;
  54350. this._vertex.y = this._shape[pt].y;
  54351. this._vertex.z = this._shape[pt].z;
  54352. if (this._computeParticleVertex) {
  54353. this.updateParticleVertex(this._particle, this._vertex, pt);
  54354. }
  54355. // positions
  54356. this._vertex.x *= this._particle.scaling.x;
  54357. this._vertex.y *= this._particle.scaling.y;
  54358. this._vertex.z *= this._particle.scaling.z;
  54359. this._vertex.x -= this._scaledPivot.x;
  54360. this._vertex.y -= this._scaledPivot.y;
  54361. this._vertex.z -= this._scaledPivot.z;
  54362. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  54363. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  54364. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54365. this._rotated.x += this._pivotBackTranslation.x;
  54366. this._rotated.y += this._pivotBackTranslation.y;
  54367. this._rotated.z += this._pivotBackTranslation.z;
  54368. 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;
  54369. 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;
  54370. 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;
  54371. if (this._computeBoundingBox) {
  54372. if (this._positions32[idx] < this._minimum.x) {
  54373. this._minimum.x = this._positions32[idx];
  54374. }
  54375. if (this._positions32[idx] > this._maximum.x) {
  54376. this._maximum.x = this._positions32[idx];
  54377. }
  54378. if (this._positions32[idx + 1] < this._minimum.y) {
  54379. this._minimum.y = this._positions32[idx + 1];
  54380. }
  54381. if (this._positions32[idx + 1] > this._maximum.y) {
  54382. this._maximum.y = this._positions32[idx + 1];
  54383. }
  54384. if (this._positions32[idx + 2] < this._minimum.z) {
  54385. this._minimum.z = this._positions32[idx + 2];
  54386. }
  54387. if (this._positions32[idx + 2] > this._maximum.z) {
  54388. this._maximum.z = this._positions32[idx + 2];
  54389. }
  54390. }
  54391. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  54392. if (!this._computeParticleVertex) {
  54393. this._normal.x = this._fixedNormal32[idx];
  54394. this._normal.y = this._fixedNormal32[idx + 1];
  54395. this._normal.z = this._fixedNormal32[idx + 2];
  54396. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  54397. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  54398. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  54399. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  54400. 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;
  54401. 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;
  54402. }
  54403. if (this._computeParticleColor && this._particle.color) {
  54404. this._colors32[colidx] = this._particle.color.r;
  54405. this._colors32[colidx + 1] = this._particle.color.g;
  54406. this._colors32[colidx + 2] = this._particle.color.b;
  54407. this._colors32[colidx + 3] = this._particle.color.a;
  54408. }
  54409. if (this._computeParticleTexture) {
  54410. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54411. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54412. }
  54413. }
  54414. }
  54415. else {
  54416. this._particle._stillInvisible = true; // mark the particle as invisible
  54417. for (pt = 0; pt < this._shape.length; pt++) {
  54418. idx = index + pt * 3;
  54419. colidx = colorIndex + pt * 4;
  54420. uvidx = uvIndex + pt * 2;
  54421. this._positions32[idx] = 0.0;
  54422. this._positions32[idx + 1] = 0.0;
  54423. this._positions32[idx + 2] = 0.0;
  54424. this._normals32[idx] = 0.0;
  54425. this._normals32[idx + 1] = 0.0;
  54426. this._normals32[idx + 2] = 0.0;
  54427. if (this._computeParticleColor && this._particle.color) {
  54428. this._colors32[colidx] = this._particle.color.r;
  54429. this._colors32[colidx + 1] = this._particle.color.g;
  54430. this._colors32[colidx + 2] = this._particle.color.b;
  54431. this._colors32[colidx + 3] = this._particle.color.a;
  54432. }
  54433. if (this._computeParticleTexture) {
  54434. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54435. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54436. }
  54437. }
  54438. }
  54439. // if the particle intersections must be computed : update the bbInfo
  54440. if (this._particlesIntersect) {
  54441. var bInfo = this._particle._boundingInfo;
  54442. var bBox = bInfo.boundingBox;
  54443. var bSphere = bInfo.boundingSphere;
  54444. if (!this._bSphereOnly) {
  54445. // place, scale and rotate the particle bbox within the SPS local system, then update it
  54446. for (var b = 0; b < bBox.vectors.length; b++) {
  54447. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  54448. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  54449. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  54450. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  54451. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  54452. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54453. 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;
  54454. 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;
  54455. 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;
  54456. }
  54457. bBox._update(this.mesh._worldMatrix);
  54458. }
  54459. // place and scale the particle bouding sphere in the SPS local system, then update it
  54460. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  54461. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  54462. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  54463. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  54464. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  54465. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  54466. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  54467. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  54468. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  54469. 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));
  54470. bSphere._update(this.mesh._worldMatrix);
  54471. }
  54472. // increment indexes for the next particle
  54473. index = idx + 3;
  54474. colorIndex = colidx + 4;
  54475. uvIndex = uvidx + 2;
  54476. }
  54477. // if the VBO must be updated
  54478. if (update) {
  54479. if (this._computeParticleColor) {
  54480. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  54481. }
  54482. if (this._computeParticleTexture) {
  54483. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  54484. }
  54485. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54486. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  54487. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  54488. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  54489. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  54490. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  54491. for (var i = 0; i < this._normals32.length; i++) {
  54492. this._fixedNormal32[i] = this._normals32[i];
  54493. }
  54494. }
  54495. if (!this.mesh.areNormalsFrozen) {
  54496. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  54497. }
  54498. }
  54499. if (this._depthSort && this._depthSortParticles) {
  54500. this.depthSortedParticles.sort(this._depthSortFunction);
  54501. var dspl = this.depthSortedParticles.length;
  54502. var sorted = 0;
  54503. var lind = 0;
  54504. var sind = 0;
  54505. var sid = 0;
  54506. for (sorted = 0; sorted < dspl; sorted++) {
  54507. lind = this.depthSortedParticles[sorted].indicesLength;
  54508. sind = this.depthSortedParticles[sorted].ind;
  54509. for (var i = 0; i < lind; i++) {
  54510. this._indices32[sid] = this._indices[sind + i];
  54511. sid++;
  54512. }
  54513. }
  54514. this.mesh.updateIndices(this._indices32);
  54515. }
  54516. }
  54517. if (this._computeBoundingBox) {
  54518. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  54519. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  54520. }
  54521. this.afterUpdateParticles(start, end, update);
  54522. return this;
  54523. };
  54524. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  54525. this._halfroll = this._roll * 0.5;
  54526. this._halfpitch = this._pitch * 0.5;
  54527. this._halfyaw = this._yaw * 0.5;
  54528. this._sinRoll = Math.sin(this._halfroll);
  54529. this._cosRoll = Math.cos(this._halfroll);
  54530. this._sinPitch = Math.sin(this._halfpitch);
  54531. this._cosPitch = Math.cos(this._halfpitch);
  54532. this._sinYaw = Math.sin(this._halfyaw);
  54533. this._cosYaw = Math.cos(this._halfyaw);
  54534. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  54535. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  54536. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  54537. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  54538. };
  54539. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  54540. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  54541. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  54542. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  54543. this._rotMatrix.m[3] = 0;
  54544. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  54545. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  54546. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  54547. this._rotMatrix.m[7] = 0;
  54548. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  54549. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  54550. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  54551. this._rotMatrix.m[11] = 0;
  54552. this._rotMatrix.m[12] = 0;
  54553. this._rotMatrix.m[13] = 0;
  54554. this._rotMatrix.m[14] = 0;
  54555. this._rotMatrix.m[15] = 1.0;
  54556. };
  54557. /**
  54558. * Disposes the SPS.
  54559. */
  54560. SolidParticleSystem.prototype.dispose = function () {
  54561. this.mesh.dispose();
  54562. this.vars = null;
  54563. // drop references to internal big arrays for the GC
  54564. this._positions = null;
  54565. this._indices = null;
  54566. this._normals = null;
  54567. this._uvs = null;
  54568. this._colors = null;
  54569. this._indices32 = null;
  54570. this._positions32 = null;
  54571. this._normals32 = null;
  54572. this._fixedNormal32 = null;
  54573. this._uvs32 = null;
  54574. this._colors32 = null;
  54575. this.pickedParticles = null;
  54576. };
  54577. /**
  54578. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  54579. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54580. * @returns the SPS.
  54581. */
  54582. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  54583. if (!this._isVisibilityBoxLocked) {
  54584. this.mesh.refreshBoundingInfo();
  54585. }
  54586. return this;
  54587. };
  54588. /**
  54589. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  54590. * @param size the size (float) of the visibility box
  54591. * note : this doesn't lock the SPS mesh bounding box.
  54592. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54593. */
  54594. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  54595. var vis = size / 2;
  54596. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  54597. };
  54598. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  54599. /**
  54600. * Gets whether the SPS as always visible or not
  54601. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54602. */
  54603. get: function () {
  54604. return this._alwaysVisible;
  54605. },
  54606. /**
  54607. * Sets the SPS as always visible or not
  54608. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54609. */
  54610. set: function (val) {
  54611. this._alwaysVisible = val;
  54612. this.mesh.alwaysSelectAsActiveMesh = val;
  54613. },
  54614. enumerable: true,
  54615. configurable: true
  54616. });
  54617. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  54618. /**
  54619. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54620. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54621. */
  54622. get: function () {
  54623. return this._isVisibilityBoxLocked;
  54624. },
  54625. /**
  54626. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54627. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54628. */
  54629. set: function (val) {
  54630. this._isVisibilityBoxLocked = val;
  54631. var boundingInfo = this.mesh.getBoundingInfo();
  54632. boundingInfo.isLocked = val;
  54633. },
  54634. enumerable: true,
  54635. configurable: true
  54636. });
  54637. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  54638. /**
  54639. * Gets if `setParticles()` computes the particle rotations or not.
  54640. * Default value : true. The SPS is faster when it's set to false.
  54641. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54642. */
  54643. get: function () {
  54644. return this._computeParticleRotation;
  54645. },
  54646. /**
  54647. * Tells to `setParticles()` to compute the particle rotations or not.
  54648. * Default value : true. The SPS is faster when it's set to false.
  54649. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54650. */
  54651. set: function (val) {
  54652. this._computeParticleRotation = val;
  54653. },
  54654. enumerable: true,
  54655. configurable: true
  54656. });
  54657. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  54658. /**
  54659. * Gets if `setParticles()` computes the particle colors or not.
  54660. * Default value : true. The SPS is faster when it's set to false.
  54661. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54662. */
  54663. get: function () {
  54664. return this._computeParticleColor;
  54665. },
  54666. /**
  54667. * Tells to `setParticles()` to compute the particle colors or not.
  54668. * Default value : true. The SPS is faster when it's set to false.
  54669. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54670. */
  54671. set: function (val) {
  54672. this._computeParticleColor = val;
  54673. },
  54674. enumerable: true,
  54675. configurable: true
  54676. });
  54677. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  54678. /**
  54679. * Gets if `setParticles()` computes the particle textures or not.
  54680. * Default value : true. The SPS is faster when it's set to false.
  54681. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  54682. */
  54683. get: function () {
  54684. return this._computeParticleTexture;
  54685. },
  54686. set: function (val) {
  54687. this._computeParticleTexture = val;
  54688. },
  54689. enumerable: true,
  54690. configurable: true
  54691. });
  54692. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  54693. /**
  54694. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  54695. * Default value : false. The SPS is faster when it's set to false.
  54696. * Note : the particle custom vertex positions aren't stored values.
  54697. */
  54698. get: function () {
  54699. return this._computeParticleVertex;
  54700. },
  54701. /**
  54702. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  54703. * Default value : false. The SPS is faster when it's set to false.
  54704. * Note : the particle custom vertex positions aren't stored values.
  54705. */
  54706. set: function (val) {
  54707. this._computeParticleVertex = val;
  54708. },
  54709. enumerable: true,
  54710. configurable: true
  54711. });
  54712. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  54713. /**
  54714. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  54715. */
  54716. get: function () {
  54717. return this._computeBoundingBox;
  54718. },
  54719. /**
  54720. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  54721. */
  54722. set: function (val) {
  54723. this._computeBoundingBox = val;
  54724. },
  54725. enumerable: true,
  54726. configurable: true
  54727. });
  54728. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  54729. /**
  54730. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  54731. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  54732. * Default : `true`
  54733. */
  54734. get: function () {
  54735. return this._depthSortParticles;
  54736. },
  54737. /**
  54738. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  54739. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  54740. * Default : `true`
  54741. */
  54742. set: function (val) {
  54743. this._depthSortParticles = val;
  54744. },
  54745. enumerable: true,
  54746. configurable: true
  54747. });
  54748. // =======================================================================
  54749. // Particle behavior logic
  54750. // these following methods may be overwritten by the user to fit his needs
  54751. /**
  54752. * This function does nothing. It may be overwritten to set all the particle first values.
  54753. * The SPS doesn't call this function, you may have to call it by your own.
  54754. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54755. */
  54756. SolidParticleSystem.prototype.initParticles = function () {
  54757. };
  54758. /**
  54759. * This function does nothing. It may be overwritten to recycle a particle.
  54760. * The SPS doesn't call this function, you may have to call it by your own.
  54761. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54762. * @param particle The particle to recycle
  54763. * @returns the recycled particle
  54764. */
  54765. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  54766. return particle;
  54767. };
  54768. /**
  54769. * Updates a particle : this function should be overwritten by the user.
  54770. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  54771. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54772. * @example : just set a particle position or velocity and recycle conditions
  54773. * @param particle The particle to update
  54774. * @returns the updated particle
  54775. */
  54776. SolidParticleSystem.prototype.updateParticle = function (particle) {
  54777. return particle;
  54778. };
  54779. /**
  54780. * Updates a vertex of a particle : it can be overwritten by the user.
  54781. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  54782. * @param particle the current particle
  54783. * @param vertex the current index of the current particle
  54784. * @param pt the index of the current vertex in the particle shape
  54785. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  54786. * @example : just set a vertex particle position
  54787. * @returns the updated vertex
  54788. */
  54789. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  54790. return vertex;
  54791. };
  54792. /**
  54793. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  54794. * This does nothing and may be overwritten by the user.
  54795. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54796. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54797. * @param update the boolean update value actually passed to setParticles()
  54798. */
  54799. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  54800. };
  54801. /**
  54802. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  54803. * This will be passed three parameters.
  54804. * This does nothing and may be overwritten by the user.
  54805. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54806. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54807. * @param update the boolean update value actually passed to setParticles()
  54808. */
  54809. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  54810. };
  54811. return SolidParticleSystem;
  54812. }());
  54813. BABYLON.SolidParticleSystem = SolidParticleSystem;
  54814. })(BABYLON || (BABYLON = {}));
  54815. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  54816. var BABYLON;
  54817. (function (BABYLON) {
  54818. var ShaderMaterial = /** @class */ (function (_super) {
  54819. __extends(ShaderMaterial, _super);
  54820. function ShaderMaterial(name, scene, shaderPath, options) {
  54821. var _this = _super.call(this, name, scene) || this;
  54822. _this._textures = {};
  54823. _this._textureArrays = {};
  54824. _this._floats = {};
  54825. _this._ints = {};
  54826. _this._floatsArrays = {};
  54827. _this._colors3 = {};
  54828. _this._colors3Arrays = {};
  54829. _this._colors4 = {};
  54830. _this._vectors2 = {};
  54831. _this._vectors3 = {};
  54832. _this._vectors4 = {};
  54833. _this._matrices = {};
  54834. _this._matrices3x3 = {};
  54835. _this._matrices2x2 = {};
  54836. _this._vectors2Arrays = {};
  54837. _this._vectors3Arrays = {};
  54838. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  54839. _this._shaderPath = shaderPath;
  54840. options.needAlphaBlending = options.needAlphaBlending || false;
  54841. options.needAlphaTesting = options.needAlphaTesting || false;
  54842. options.attributes = options.attributes || ["position", "normal", "uv"];
  54843. options.uniforms = options.uniforms || ["worldViewProjection"];
  54844. options.uniformBuffers = options.uniformBuffers || [];
  54845. options.samplers = options.samplers || [];
  54846. options.defines = options.defines || [];
  54847. _this._options = options;
  54848. return _this;
  54849. }
  54850. ShaderMaterial.prototype.getClassName = function () {
  54851. return "ShaderMaterial";
  54852. };
  54853. ShaderMaterial.prototype.needAlphaBlending = function () {
  54854. return this._options.needAlphaBlending;
  54855. };
  54856. ShaderMaterial.prototype.needAlphaTesting = function () {
  54857. return this._options.needAlphaTesting;
  54858. };
  54859. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  54860. if (this._options.uniforms.indexOf(uniformName) === -1) {
  54861. this._options.uniforms.push(uniformName);
  54862. }
  54863. };
  54864. ShaderMaterial.prototype.setTexture = function (name, texture) {
  54865. if (this._options.samplers.indexOf(name) === -1) {
  54866. this._options.samplers.push(name);
  54867. }
  54868. this._textures[name] = texture;
  54869. return this;
  54870. };
  54871. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  54872. if (this._options.samplers.indexOf(name) === -1) {
  54873. this._options.samplers.push(name);
  54874. }
  54875. this._checkUniform(name);
  54876. this._textureArrays[name] = textures;
  54877. return this;
  54878. };
  54879. ShaderMaterial.prototype.setFloat = function (name, value) {
  54880. this._checkUniform(name);
  54881. this._floats[name] = value;
  54882. return this;
  54883. };
  54884. ShaderMaterial.prototype.setInt = function (name, value) {
  54885. this._checkUniform(name);
  54886. this._ints[name] = value;
  54887. return this;
  54888. };
  54889. ShaderMaterial.prototype.setFloats = function (name, value) {
  54890. this._checkUniform(name);
  54891. this._floatsArrays[name] = value;
  54892. return this;
  54893. };
  54894. ShaderMaterial.prototype.setColor3 = function (name, value) {
  54895. this._checkUniform(name);
  54896. this._colors3[name] = value;
  54897. return this;
  54898. };
  54899. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  54900. this._checkUniform(name);
  54901. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  54902. color.toArray(arr, arr.length);
  54903. return arr;
  54904. }, []);
  54905. return this;
  54906. };
  54907. ShaderMaterial.prototype.setColor4 = function (name, value) {
  54908. this._checkUniform(name);
  54909. this._colors4[name] = value;
  54910. return this;
  54911. };
  54912. ShaderMaterial.prototype.setVector2 = function (name, value) {
  54913. this._checkUniform(name);
  54914. this._vectors2[name] = value;
  54915. return this;
  54916. };
  54917. ShaderMaterial.prototype.setVector3 = function (name, value) {
  54918. this._checkUniform(name);
  54919. this._vectors3[name] = value;
  54920. return this;
  54921. };
  54922. ShaderMaterial.prototype.setVector4 = function (name, value) {
  54923. this._checkUniform(name);
  54924. this._vectors4[name] = value;
  54925. return this;
  54926. };
  54927. ShaderMaterial.prototype.setMatrix = function (name, value) {
  54928. this._checkUniform(name);
  54929. this._matrices[name] = value;
  54930. return this;
  54931. };
  54932. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  54933. this._checkUniform(name);
  54934. this._matrices3x3[name] = value;
  54935. return this;
  54936. };
  54937. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  54938. this._checkUniform(name);
  54939. this._matrices2x2[name] = value;
  54940. return this;
  54941. };
  54942. ShaderMaterial.prototype.setArray2 = function (name, value) {
  54943. this._checkUniform(name);
  54944. this._vectors2Arrays[name] = value;
  54945. return this;
  54946. };
  54947. ShaderMaterial.prototype.setArray3 = function (name, value) {
  54948. this._checkUniform(name);
  54949. this._vectors3Arrays[name] = value;
  54950. return this;
  54951. };
  54952. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  54953. if (!mesh) {
  54954. return true;
  54955. }
  54956. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  54957. return false;
  54958. }
  54959. return false;
  54960. };
  54961. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  54962. var scene = this.getScene();
  54963. var engine = scene.getEngine();
  54964. if (!this.checkReadyOnEveryCall) {
  54965. if (this._renderId === scene.getRenderId()) {
  54966. if (this._checkCache(scene, mesh, useInstances)) {
  54967. return true;
  54968. }
  54969. }
  54970. }
  54971. // Instances
  54972. var defines = [];
  54973. var attribs = [];
  54974. var fallbacks = new BABYLON.EffectFallbacks();
  54975. if (useInstances) {
  54976. defines.push("#define INSTANCES");
  54977. }
  54978. for (var index = 0; index < this._options.defines.length; index++) {
  54979. defines.push(this._options.defines[index]);
  54980. }
  54981. for (var index = 0; index < this._options.attributes.length; index++) {
  54982. attribs.push(this._options.attributes[index]);
  54983. }
  54984. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  54985. attribs.push(BABYLON.VertexBuffer.ColorKind);
  54986. defines.push("#define VERTEXCOLOR");
  54987. }
  54988. // Bones
  54989. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  54990. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  54991. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  54992. if (mesh.numBoneInfluencers > 4) {
  54993. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  54994. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  54995. }
  54996. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  54997. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  54998. fallbacks.addCPUSkinningFallback(0, mesh);
  54999. if (this._options.uniforms.indexOf("mBones") === -1) {
  55000. this._options.uniforms.push("mBones");
  55001. }
  55002. }
  55003. else {
  55004. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55005. }
  55006. // Textures
  55007. for (var name in this._textures) {
  55008. if (!this._textures[name].isReady()) {
  55009. return false;
  55010. }
  55011. }
  55012. // Alpha test
  55013. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  55014. defines.push("#define ALPHATEST");
  55015. }
  55016. var previousEffect = this._effect;
  55017. var join = defines.join("\n");
  55018. this._effect = engine.createEffect(this._shaderPath, {
  55019. attributes: attribs,
  55020. uniformsNames: this._options.uniforms,
  55021. uniformBuffersNames: this._options.uniformBuffers,
  55022. samplers: this._options.samplers,
  55023. defines: join,
  55024. fallbacks: fallbacks,
  55025. onCompiled: this.onCompiled,
  55026. onError: this.onError
  55027. }, engine);
  55028. if (!this._effect.isReady()) {
  55029. return false;
  55030. }
  55031. if (previousEffect !== this._effect) {
  55032. scene.resetCachedMaterial();
  55033. }
  55034. this._renderId = scene.getRenderId();
  55035. return true;
  55036. };
  55037. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  55038. var scene = this.getScene();
  55039. if (!this._effect) {
  55040. return;
  55041. }
  55042. if (this._options.uniforms.indexOf("world") !== -1) {
  55043. this._effect.setMatrix("world", world);
  55044. }
  55045. if (this._options.uniforms.indexOf("worldView") !== -1) {
  55046. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  55047. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  55048. }
  55049. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  55050. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  55051. }
  55052. };
  55053. ShaderMaterial.prototype.bind = function (world, mesh) {
  55054. // Std values
  55055. this.bindOnlyWorldMatrix(world);
  55056. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  55057. if (this._options.uniforms.indexOf("view") !== -1) {
  55058. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  55059. }
  55060. if (this._options.uniforms.indexOf("projection") !== -1) {
  55061. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  55062. }
  55063. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  55064. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  55065. }
  55066. // Bones
  55067. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  55068. var name;
  55069. // Texture
  55070. for (name in this._textures) {
  55071. this._effect.setTexture(name, this._textures[name]);
  55072. }
  55073. // Texture arrays
  55074. for (name in this._textureArrays) {
  55075. this._effect.setTextureArray(name, this._textureArrays[name]);
  55076. }
  55077. // Int
  55078. for (name in this._ints) {
  55079. this._effect.setInt(name, this._ints[name]);
  55080. }
  55081. // Float
  55082. for (name in this._floats) {
  55083. this._effect.setFloat(name, this._floats[name]);
  55084. }
  55085. // Floats
  55086. for (name in this._floatsArrays) {
  55087. this._effect.setArray(name, this._floatsArrays[name]);
  55088. }
  55089. // Color3
  55090. for (name in this._colors3) {
  55091. this._effect.setColor3(name, this._colors3[name]);
  55092. }
  55093. for (name in this._colors3Arrays) {
  55094. this._effect.setArray3(name, this._colors3Arrays[name]);
  55095. }
  55096. // Color4
  55097. for (name in this._colors4) {
  55098. var color = this._colors4[name];
  55099. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  55100. }
  55101. // Vector2
  55102. for (name in this._vectors2) {
  55103. this._effect.setVector2(name, this._vectors2[name]);
  55104. }
  55105. // Vector3
  55106. for (name in this._vectors3) {
  55107. this._effect.setVector3(name, this._vectors3[name]);
  55108. }
  55109. // Vector4
  55110. for (name in this._vectors4) {
  55111. this._effect.setVector4(name, this._vectors4[name]);
  55112. }
  55113. // Matrix
  55114. for (name in this._matrices) {
  55115. this._effect.setMatrix(name, this._matrices[name]);
  55116. }
  55117. // Matrix 3x3
  55118. for (name in this._matrices3x3) {
  55119. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  55120. }
  55121. // Matrix 2x2
  55122. for (name in this._matrices2x2) {
  55123. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  55124. }
  55125. // Vector2Array
  55126. for (name in this._vectors2Arrays) {
  55127. this._effect.setArray2(name, this._vectors2Arrays[name]);
  55128. }
  55129. // Vector3Array
  55130. for (name in this._vectors3Arrays) {
  55131. this._effect.setArray3(name, this._vectors3Arrays[name]);
  55132. }
  55133. }
  55134. this._afterBind(mesh);
  55135. };
  55136. ShaderMaterial.prototype.getActiveTextures = function () {
  55137. var activeTextures = _super.prototype.getActiveTextures.call(this);
  55138. for (var name in this._textures) {
  55139. activeTextures.push(this._textures[name]);
  55140. }
  55141. for (var name in this._textureArrays) {
  55142. var array = this._textureArrays[name];
  55143. for (var index = 0; index < array.length; index++) {
  55144. activeTextures.push(array[index]);
  55145. }
  55146. }
  55147. return activeTextures;
  55148. };
  55149. ShaderMaterial.prototype.hasTexture = function (texture) {
  55150. if (_super.prototype.hasTexture.call(this, texture)) {
  55151. return true;
  55152. }
  55153. for (var name in this._textures) {
  55154. if (this._textures[name] === texture) {
  55155. return true;
  55156. }
  55157. }
  55158. for (var name in this._textureArrays) {
  55159. var array = this._textureArrays[name];
  55160. for (var index = 0; index < array.length; index++) {
  55161. if (array[index] === texture) {
  55162. return true;
  55163. }
  55164. }
  55165. }
  55166. return false;
  55167. };
  55168. ShaderMaterial.prototype.clone = function (name) {
  55169. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  55170. return newShaderMaterial;
  55171. };
  55172. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  55173. if (forceDisposeTextures) {
  55174. var name;
  55175. for (name in this._textures) {
  55176. this._textures[name].dispose();
  55177. }
  55178. for (name in this._textureArrays) {
  55179. var array = this._textureArrays[name];
  55180. for (var index = 0; index < array.length; index++) {
  55181. array[index].dispose();
  55182. }
  55183. }
  55184. }
  55185. this._textures = {};
  55186. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  55187. };
  55188. ShaderMaterial.prototype.serialize = function () {
  55189. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  55190. serializationObject.customType = "BABYLON.ShaderMaterial";
  55191. serializationObject.options = this._options;
  55192. serializationObject.shaderPath = this._shaderPath;
  55193. var name;
  55194. // Texture
  55195. serializationObject.textures = {};
  55196. for (name in this._textures) {
  55197. serializationObject.textures[name] = this._textures[name].serialize();
  55198. }
  55199. // Texture arrays
  55200. serializationObject.textureArrays = {};
  55201. for (name in this._textureArrays) {
  55202. serializationObject.textureArrays[name] = [];
  55203. var array = this._textureArrays[name];
  55204. for (var index = 0; index < array.length; index++) {
  55205. serializationObject.textureArrays[name].push(array[index].serialize());
  55206. }
  55207. }
  55208. // Float
  55209. serializationObject.floats = {};
  55210. for (name in this._floats) {
  55211. serializationObject.floats[name] = this._floats[name];
  55212. }
  55213. // Float s
  55214. serializationObject.FloatArrays = {};
  55215. for (name in this._floatsArrays) {
  55216. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  55217. }
  55218. // Color3
  55219. serializationObject.colors3 = {};
  55220. for (name in this._colors3) {
  55221. serializationObject.colors3[name] = this._colors3[name].asArray();
  55222. }
  55223. // Color3 array
  55224. serializationObject.colors3Arrays = {};
  55225. for (name in this._colors3Arrays) {
  55226. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  55227. }
  55228. // Color4
  55229. serializationObject.colors4 = {};
  55230. for (name in this._colors4) {
  55231. serializationObject.colors4[name] = this._colors4[name].asArray();
  55232. }
  55233. // Vector2
  55234. serializationObject.vectors2 = {};
  55235. for (name in this._vectors2) {
  55236. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  55237. }
  55238. // Vector3
  55239. serializationObject.vectors3 = {};
  55240. for (name in this._vectors3) {
  55241. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  55242. }
  55243. // Vector4
  55244. serializationObject.vectors4 = {};
  55245. for (name in this._vectors4) {
  55246. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  55247. }
  55248. // Matrix
  55249. serializationObject.matrices = {};
  55250. for (name in this._matrices) {
  55251. serializationObject.matrices[name] = this._matrices[name].asArray();
  55252. }
  55253. // Matrix 3x3
  55254. serializationObject.matrices3x3 = {};
  55255. for (name in this._matrices3x3) {
  55256. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  55257. }
  55258. // Matrix 2x2
  55259. serializationObject.matrices2x2 = {};
  55260. for (name in this._matrices2x2) {
  55261. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  55262. }
  55263. // Vector2Array
  55264. serializationObject.vectors2Arrays = {};
  55265. for (name in this._vectors2Arrays) {
  55266. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  55267. }
  55268. // Vector3Array
  55269. serializationObject.vectors3Arrays = {};
  55270. for (name in this._vectors3Arrays) {
  55271. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  55272. }
  55273. return serializationObject;
  55274. };
  55275. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  55276. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  55277. var name;
  55278. // Texture
  55279. for (name in source.textures) {
  55280. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  55281. }
  55282. // Texture arrays
  55283. for (name in source.textureArrays) {
  55284. var array = source.textureArrays[name];
  55285. var textureArray = new Array();
  55286. for (var index = 0; index < array.length; index++) {
  55287. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  55288. }
  55289. material.setTextureArray(name, textureArray);
  55290. }
  55291. // Float
  55292. for (name in source.floats) {
  55293. material.setFloat(name, source.floats[name]);
  55294. }
  55295. // Float s
  55296. for (name in source.floatsArrays) {
  55297. material.setFloats(name, source.floatsArrays[name]);
  55298. }
  55299. // Color3
  55300. for (name in source.colors3) {
  55301. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  55302. }
  55303. // Color3 arrays
  55304. for (name in source.colors3Arrays) {
  55305. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  55306. if (i % 3 === 0) {
  55307. arr.push([num]);
  55308. }
  55309. else {
  55310. arr[arr.length - 1].push(num);
  55311. }
  55312. return arr;
  55313. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  55314. material.setColor3Array(name, colors);
  55315. }
  55316. // Color4
  55317. for (name in source.colors4) {
  55318. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  55319. }
  55320. // Vector2
  55321. for (name in source.vectors2) {
  55322. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  55323. }
  55324. // Vector3
  55325. for (name in source.vectors3) {
  55326. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  55327. }
  55328. // Vector4
  55329. for (name in source.vectors4) {
  55330. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  55331. }
  55332. // Matrix
  55333. for (name in source.matrices) {
  55334. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  55335. }
  55336. // Matrix 3x3
  55337. for (name in source.matrices3x3) {
  55338. material.setMatrix3x3(name, source.matrices3x3[name]);
  55339. }
  55340. // Matrix 2x2
  55341. for (name in source.matrices2x2) {
  55342. material.setMatrix2x2(name, source.matrices2x2[name]);
  55343. }
  55344. // Vector2Array
  55345. for (name in source.vectors2Arrays) {
  55346. material.setArray2(name, source.vectors2Arrays[name]);
  55347. }
  55348. // Vector3Array
  55349. for (name in source.vectors3Arrays) {
  55350. material.setArray3(name, source.vectors3Arrays[name]);
  55351. }
  55352. return material;
  55353. };
  55354. return ShaderMaterial;
  55355. }(BABYLON.Material));
  55356. BABYLON.ShaderMaterial = ShaderMaterial;
  55357. })(BABYLON || (BABYLON = {}));
  55358. //# sourceMappingURL=babylon.shaderMaterial.js.map
  55359. var BABYLON;
  55360. (function (BABYLON) {
  55361. var GroundMesh = /** @class */ (function (_super) {
  55362. __extends(GroundMesh, _super);
  55363. function GroundMesh(name, scene) {
  55364. var _this = _super.call(this, name, scene) || this;
  55365. _this.generateOctree = false;
  55366. return _this;
  55367. }
  55368. GroundMesh.prototype.getClassName = function () {
  55369. return "GroundMesh";
  55370. };
  55371. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  55372. get: function () {
  55373. return Math.min(this._subdivisionsX, this._subdivisionsY);
  55374. },
  55375. enumerable: true,
  55376. configurable: true
  55377. });
  55378. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  55379. get: function () {
  55380. return this._subdivisionsX;
  55381. },
  55382. enumerable: true,
  55383. configurable: true
  55384. });
  55385. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  55386. get: function () {
  55387. return this._subdivisionsY;
  55388. },
  55389. enumerable: true,
  55390. configurable: true
  55391. });
  55392. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  55393. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  55394. this._subdivisionsX = chunksCount;
  55395. this._subdivisionsY = chunksCount;
  55396. this.subdivide(chunksCount);
  55397. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  55398. };
  55399. /**
  55400. * Returns a height (y) value in the Worl system :
  55401. * the ground altitude at the coordinates (x, z) expressed in the World system.
  55402. * Returns the ground y position if (x, z) are outside the ground surface.
  55403. */
  55404. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  55405. var world = this.getWorldMatrix();
  55406. var invMat = BABYLON.Tmp.Matrix[5];
  55407. world.invertToRef(invMat);
  55408. var tmpVect = BABYLON.Tmp.Vector3[8];
  55409. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  55410. x = tmpVect.x;
  55411. z = tmpVect.z;
  55412. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55413. return this.position.y;
  55414. }
  55415. if (!this._heightQuads || this._heightQuads.length == 0) {
  55416. this._initHeightQuads();
  55417. this._computeHeightQuads();
  55418. }
  55419. var facet = this._getFacetAt(x, z);
  55420. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  55421. // return y in the World system
  55422. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  55423. return tmpVect.y;
  55424. };
  55425. /**
  55426. * Returns a normalized vector (Vector3) orthogonal to the ground
  55427. * at the ground coordinates (x, z) expressed in the World system.
  55428. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  55429. */
  55430. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  55431. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  55432. this.getNormalAtCoordinatesToRef(x, z, normal);
  55433. return normal;
  55434. };
  55435. /**
  55436. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  55437. * at the ground coordinates (x, z) expressed in the World system.
  55438. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  55439. * Returns the GroundMesh.
  55440. */
  55441. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  55442. var world = this.getWorldMatrix();
  55443. var tmpMat = BABYLON.Tmp.Matrix[5];
  55444. world.invertToRef(tmpMat);
  55445. var tmpVect = BABYLON.Tmp.Vector3[8];
  55446. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  55447. x = tmpVect.x;
  55448. z = tmpVect.z;
  55449. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55450. return this;
  55451. }
  55452. if (!this._heightQuads || this._heightQuads.length == 0) {
  55453. this._initHeightQuads();
  55454. this._computeHeightQuads();
  55455. }
  55456. var facet = this._getFacetAt(x, z);
  55457. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  55458. return this;
  55459. };
  55460. /**
  55461. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  55462. * if the ground has been updated.
  55463. * This can be used in the render loop.
  55464. * Returns the GroundMesh.
  55465. */
  55466. GroundMesh.prototype.updateCoordinateHeights = function () {
  55467. if (!this._heightQuads || this._heightQuads.length == 0) {
  55468. this._initHeightQuads();
  55469. }
  55470. this._computeHeightQuads();
  55471. return this;
  55472. };
  55473. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  55474. GroundMesh.prototype._getFacetAt = function (x, z) {
  55475. // retrieve col and row from x, z coordinates in the ground local system
  55476. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  55477. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  55478. var quad = this._heightQuads[row * this._subdivisionsX + col];
  55479. var facet;
  55480. if (z < quad.slope.x * x + quad.slope.y) {
  55481. facet = quad.facet1;
  55482. }
  55483. else {
  55484. facet = quad.facet2;
  55485. }
  55486. return facet;
  55487. };
  55488. // Creates and populates the heightMap array with "facet" elements :
  55489. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  55490. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55491. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55492. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55493. // Returns the GroundMesh.
  55494. GroundMesh.prototype._initHeightQuads = function () {
  55495. var subdivisionsX = this._subdivisionsX;
  55496. var subdivisionsY = this._subdivisionsY;
  55497. this._heightQuads = new Array();
  55498. for (var row = 0; row < subdivisionsY; row++) {
  55499. for (var col = 0; col < subdivisionsX; col++) {
  55500. 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) };
  55501. this._heightQuads[row * subdivisionsX + col] = quad;
  55502. }
  55503. }
  55504. return this;
  55505. };
  55506. // Compute each quad element values and update the the heightMap array :
  55507. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55508. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55509. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55510. // Returns the GroundMesh.
  55511. GroundMesh.prototype._computeHeightQuads = function () {
  55512. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55513. if (!positions) {
  55514. return this;
  55515. }
  55516. var v1 = BABYLON.Tmp.Vector3[3];
  55517. var v2 = BABYLON.Tmp.Vector3[2];
  55518. var v3 = BABYLON.Tmp.Vector3[1];
  55519. var v4 = BABYLON.Tmp.Vector3[0];
  55520. var v1v2 = BABYLON.Tmp.Vector3[4];
  55521. var v1v3 = BABYLON.Tmp.Vector3[5];
  55522. var v1v4 = BABYLON.Tmp.Vector3[6];
  55523. var norm1 = BABYLON.Tmp.Vector3[7];
  55524. var norm2 = BABYLON.Tmp.Vector3[8];
  55525. var i = 0;
  55526. var j = 0;
  55527. var k = 0;
  55528. var cd = 0; // 2D slope coefficient : z = cd * x + h
  55529. var h = 0;
  55530. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  55531. var d2 = 0;
  55532. var subdivisionsX = this._subdivisionsX;
  55533. var subdivisionsY = this._subdivisionsY;
  55534. for (var row = 0; row < subdivisionsY; row++) {
  55535. for (var col = 0; col < subdivisionsX; col++) {
  55536. i = col * 3;
  55537. j = row * (subdivisionsX + 1) * 3;
  55538. k = (row + 1) * (subdivisionsX + 1) * 3;
  55539. v1.x = positions[j + i];
  55540. v1.y = positions[j + i + 1];
  55541. v1.z = positions[j + i + 2];
  55542. v2.x = positions[j + i + 3];
  55543. v2.y = positions[j + i + 4];
  55544. v2.z = positions[j + i + 5];
  55545. v3.x = positions[k + i];
  55546. v3.y = positions[k + i + 1];
  55547. v3.z = positions[k + i + 2];
  55548. v4.x = positions[k + i + 3];
  55549. v4.y = positions[k + i + 4];
  55550. v4.z = positions[k + i + 5];
  55551. // 2D slope V1V4
  55552. cd = (v4.z - v1.z) / (v4.x - v1.x);
  55553. h = v1.z - cd * v1.x; // v1 belongs to the slope
  55554. // facet equations :
  55555. // we compute each facet normal vector
  55556. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  55557. // we compute the value d by applying the equation to v1 which belongs to the plane
  55558. // then we store the facet equation in a Vector4
  55559. v2.subtractToRef(v1, v1v2);
  55560. v3.subtractToRef(v1, v1v3);
  55561. v4.subtractToRef(v1, v1v4);
  55562. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  55563. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  55564. norm1.normalize();
  55565. norm2.normalize();
  55566. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  55567. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  55568. var quad = this._heightQuads[row * subdivisionsX + col];
  55569. quad.slope.copyFromFloats(cd, h);
  55570. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  55571. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  55572. }
  55573. }
  55574. return this;
  55575. };
  55576. GroundMesh.prototype.serialize = function (serializationObject) {
  55577. _super.prototype.serialize.call(this, serializationObject);
  55578. serializationObject.subdivisionsX = this._subdivisionsX;
  55579. serializationObject.subdivisionsY = this._subdivisionsY;
  55580. serializationObject.minX = this._minX;
  55581. serializationObject.maxX = this._maxX;
  55582. serializationObject.minZ = this._minZ;
  55583. serializationObject.maxZ = this._maxZ;
  55584. serializationObject.width = this._width;
  55585. serializationObject.height = this._height;
  55586. };
  55587. GroundMesh.Parse = function (parsedMesh, scene) {
  55588. var result = new GroundMesh(parsedMesh.name, scene);
  55589. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  55590. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  55591. result._minX = parsedMesh.minX;
  55592. result._maxX = parsedMesh.maxX;
  55593. result._minZ = parsedMesh.minZ;
  55594. result._maxZ = parsedMesh.maxZ;
  55595. result._width = parsedMesh.width;
  55596. result._height = parsedMesh.height;
  55597. return result;
  55598. };
  55599. return GroundMesh;
  55600. }(BABYLON.Mesh));
  55601. BABYLON.GroundMesh = GroundMesh;
  55602. })(BABYLON || (BABYLON = {}));
  55603. //# sourceMappingURL=babylon.groundMesh.js.map
  55604. var BABYLON;
  55605. (function (BABYLON) {
  55606. /**
  55607. * Creates an instance based on a source mesh.
  55608. */
  55609. var InstancedMesh = /** @class */ (function (_super) {
  55610. __extends(InstancedMesh, _super);
  55611. function InstancedMesh(name, source) {
  55612. var _this = _super.call(this, name, source.getScene()) || this;
  55613. source.instances.push(_this);
  55614. _this._sourceMesh = source;
  55615. _this.position.copyFrom(source.position);
  55616. _this.rotation.copyFrom(source.rotation);
  55617. _this.scaling.copyFrom(source.scaling);
  55618. if (source.rotationQuaternion) {
  55619. _this.rotationQuaternion = source.rotationQuaternion.clone();
  55620. }
  55621. _this.infiniteDistance = source.infiniteDistance;
  55622. _this.setPivotMatrix(source.getPivotMatrix());
  55623. _this.refreshBoundingInfo();
  55624. _this._syncSubMeshes();
  55625. return _this;
  55626. }
  55627. /**
  55628. * Returns the string "InstancedMesh".
  55629. */
  55630. InstancedMesh.prototype.getClassName = function () {
  55631. return "InstancedMesh";
  55632. };
  55633. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  55634. // Methods
  55635. get: function () {
  55636. return this._sourceMesh.receiveShadows;
  55637. },
  55638. enumerable: true,
  55639. configurable: true
  55640. });
  55641. Object.defineProperty(InstancedMesh.prototype, "material", {
  55642. get: function () {
  55643. return this._sourceMesh.material;
  55644. },
  55645. enumerable: true,
  55646. configurable: true
  55647. });
  55648. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  55649. get: function () {
  55650. return this._sourceMesh.visibility;
  55651. },
  55652. enumerable: true,
  55653. configurable: true
  55654. });
  55655. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  55656. get: function () {
  55657. return this._sourceMesh.skeleton;
  55658. },
  55659. enumerable: true,
  55660. configurable: true
  55661. });
  55662. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  55663. get: function () {
  55664. return this._sourceMesh.renderingGroupId;
  55665. },
  55666. set: function (value) {
  55667. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  55668. return;
  55669. }
  55670. //no-op with warning
  55671. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  55672. },
  55673. enumerable: true,
  55674. configurable: true
  55675. });
  55676. /**
  55677. * Returns the total number of vertices (integer).
  55678. */
  55679. InstancedMesh.prototype.getTotalVertices = function () {
  55680. return this._sourceMesh.getTotalVertices();
  55681. };
  55682. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  55683. get: function () {
  55684. return this._sourceMesh;
  55685. },
  55686. enumerable: true,
  55687. configurable: true
  55688. });
  55689. /**
  55690. * Is this node ready to be used/rendered
  55691. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  55692. * @return {boolean} is it ready
  55693. */
  55694. InstancedMesh.prototype.isReady = function (completeCheck) {
  55695. if (completeCheck === void 0) { completeCheck = false; }
  55696. return this._sourceMesh.isReady(completeCheck, true);
  55697. };
  55698. /**
  55699. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  55700. */
  55701. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  55702. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  55703. };
  55704. /**
  55705. * Sets the vertex data of the mesh geometry for the requested `kind`.
  55706. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  55707. * The `data` are either a numeric array either a Float32Array.
  55708. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  55709. * 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).
  55710. * Note that a new underlying VertexBuffer object is created each call.
  55711. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  55712. *
  55713. * Possible `kind` values :
  55714. * - BABYLON.VertexBuffer.PositionKind
  55715. * - BABYLON.VertexBuffer.UVKind
  55716. * - BABYLON.VertexBuffer.UV2Kind
  55717. * - BABYLON.VertexBuffer.UV3Kind
  55718. * - BABYLON.VertexBuffer.UV4Kind
  55719. * - BABYLON.VertexBuffer.UV5Kind
  55720. * - BABYLON.VertexBuffer.UV6Kind
  55721. * - BABYLON.VertexBuffer.ColorKind
  55722. * - BABYLON.VertexBuffer.MatricesIndicesKind
  55723. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  55724. * - BABYLON.VertexBuffer.MatricesWeightsKind
  55725. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  55726. *
  55727. * Returns the Mesh.
  55728. */
  55729. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  55730. if (this.sourceMesh) {
  55731. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  55732. }
  55733. return this.sourceMesh;
  55734. };
  55735. /**
  55736. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  55737. * If the mesh has no geometry, it is simply returned as it is.
  55738. * The `data` are either a numeric array either a Float32Array.
  55739. * No new underlying VertexBuffer object is created.
  55740. * 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.
  55741. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  55742. *
  55743. * Possible `kind` values :
  55744. * - BABYLON.VertexBuffer.PositionKind
  55745. * - BABYLON.VertexBuffer.UVKind
  55746. * - BABYLON.VertexBuffer.UV2Kind
  55747. * - BABYLON.VertexBuffer.UV3Kind
  55748. * - BABYLON.VertexBuffer.UV4Kind
  55749. * - BABYLON.VertexBuffer.UV5Kind
  55750. * - BABYLON.VertexBuffer.UV6Kind
  55751. * - BABYLON.VertexBuffer.ColorKind
  55752. * - BABYLON.VertexBuffer.MatricesIndicesKind
  55753. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  55754. * - BABYLON.VertexBuffer.MatricesWeightsKind
  55755. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  55756. *
  55757. * Returns the Mesh.
  55758. */
  55759. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  55760. if (this.sourceMesh) {
  55761. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  55762. }
  55763. return this.sourceMesh;
  55764. };
  55765. /**
  55766. * Sets the mesh indices.
  55767. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  55768. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  55769. * This method creates a new index buffer each call.
  55770. * Returns the Mesh.
  55771. */
  55772. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  55773. if (totalVertices === void 0) { totalVertices = null; }
  55774. if (this.sourceMesh) {
  55775. this.sourceMesh.setIndices(indices, totalVertices);
  55776. }
  55777. return this.sourceMesh;
  55778. };
  55779. /**
  55780. * Boolean : True if the mesh owns the requested kind of data.
  55781. */
  55782. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  55783. return this._sourceMesh.isVerticesDataPresent(kind);
  55784. };
  55785. /**
  55786. * Returns an array of indices (IndicesArray).
  55787. */
  55788. InstancedMesh.prototype.getIndices = function () {
  55789. return this._sourceMesh.getIndices();
  55790. };
  55791. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  55792. get: function () {
  55793. return this._sourceMesh._positions;
  55794. },
  55795. enumerable: true,
  55796. configurable: true
  55797. });
  55798. /**
  55799. * Sets a new updated BoundingInfo to the mesh.
  55800. * Returns the mesh.
  55801. */
  55802. InstancedMesh.prototype.refreshBoundingInfo = function () {
  55803. var meshBB = this._sourceMesh.getBoundingInfo();
  55804. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  55805. this._updateBoundingInfo();
  55806. return this;
  55807. };
  55808. InstancedMesh.prototype._preActivate = function () {
  55809. if (this._currentLOD) {
  55810. this._currentLOD._preActivate();
  55811. }
  55812. return this;
  55813. };
  55814. InstancedMesh.prototype._activate = function (renderId) {
  55815. if (this._currentLOD) {
  55816. this._currentLOD._registerInstanceForRenderId(this, renderId);
  55817. }
  55818. return this;
  55819. };
  55820. /**
  55821. * Returns the current associated LOD AbstractMesh.
  55822. */
  55823. InstancedMesh.prototype.getLOD = function (camera) {
  55824. if (!camera) {
  55825. return this;
  55826. }
  55827. var boundingInfo = this.getBoundingInfo();
  55828. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  55829. if (this._currentLOD === this.sourceMesh) {
  55830. return this;
  55831. }
  55832. return this._currentLOD;
  55833. };
  55834. InstancedMesh.prototype._syncSubMeshes = function () {
  55835. this.releaseSubMeshes();
  55836. if (this._sourceMesh.subMeshes) {
  55837. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  55838. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  55839. }
  55840. }
  55841. return this;
  55842. };
  55843. InstancedMesh.prototype._generatePointsArray = function () {
  55844. return this._sourceMesh._generatePointsArray();
  55845. };
  55846. /**
  55847. * Creates a new InstancedMesh from the current mesh.
  55848. * - name (string) : the cloned mesh name
  55849. * - newParent (optional Node) : the optional Node to parent the clone to.
  55850. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  55851. *
  55852. * Returns the clone.
  55853. */
  55854. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  55855. var result = this._sourceMesh.createInstance(name);
  55856. // Deep copy
  55857. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  55858. // Bounding info
  55859. this.refreshBoundingInfo();
  55860. // Parent
  55861. if (newParent) {
  55862. result.parent = newParent;
  55863. }
  55864. if (!doNotCloneChildren) {
  55865. // Children
  55866. for (var index = 0; index < this.getScene().meshes.length; index++) {
  55867. var mesh = this.getScene().meshes[index];
  55868. if (mesh.parent === this) {
  55869. mesh.clone(mesh.name, result);
  55870. }
  55871. }
  55872. }
  55873. result.computeWorldMatrix(true);
  55874. return result;
  55875. };
  55876. /**
  55877. * Disposes the InstancedMesh.
  55878. * Returns nothing.
  55879. */
  55880. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  55881. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  55882. // Remove from mesh
  55883. var index = this._sourceMesh.instances.indexOf(this);
  55884. this._sourceMesh.instances.splice(index, 1);
  55885. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  55886. };
  55887. return InstancedMesh;
  55888. }(BABYLON.AbstractMesh));
  55889. BABYLON.InstancedMesh = InstancedMesh;
  55890. })(BABYLON || (BABYLON = {}));
  55891. //# sourceMappingURL=babylon.instancedMesh.js.map
  55892. var BABYLON;
  55893. (function (BABYLON) {
  55894. var LinesMesh = /** @class */ (function (_super) {
  55895. __extends(LinesMesh, _super);
  55896. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  55897. if (scene === void 0) { scene = null; }
  55898. if (parent === void 0) { parent = null; }
  55899. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  55900. _this.useVertexColor = useVertexColor;
  55901. _this.useVertexAlpha = useVertexAlpha;
  55902. _this.color = new BABYLON.Color3(1, 1, 1);
  55903. _this.alpha = 1;
  55904. if (source) {
  55905. _this.color = source.color.clone();
  55906. _this.alpha = source.alpha;
  55907. _this.useVertexColor = source.useVertexColor;
  55908. _this.useVertexAlpha = source.useVertexAlpha;
  55909. }
  55910. _this._intersectionThreshold = 0.1;
  55911. var defines = [];
  55912. var options = {
  55913. attributes: [BABYLON.VertexBuffer.PositionKind],
  55914. uniforms: ["world", "viewProjection"],
  55915. needAlphaBlending: true,
  55916. defines: defines
  55917. };
  55918. if (useVertexAlpha === false) {
  55919. options.needAlphaBlending = false;
  55920. }
  55921. if (!useVertexColor) {
  55922. options.uniforms.push("color");
  55923. }
  55924. else {
  55925. options.defines.push("#define VERTEXCOLOR");
  55926. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  55927. }
  55928. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  55929. return _this;
  55930. }
  55931. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  55932. /**
  55933. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  55934. * This margin is expressed in world space coordinates, so its value may vary.
  55935. * Default value is 0.1
  55936. * @returns the intersection Threshold value.
  55937. */
  55938. get: function () {
  55939. return this._intersectionThreshold;
  55940. },
  55941. /**
  55942. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  55943. * This margin is expressed in world space coordinates, so its value may vary.
  55944. * @param value the new threshold to apply
  55945. */
  55946. set: function (value) {
  55947. if (this._intersectionThreshold === value) {
  55948. return;
  55949. }
  55950. this._intersectionThreshold = value;
  55951. if (this.geometry) {
  55952. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  55953. }
  55954. },
  55955. enumerable: true,
  55956. configurable: true
  55957. });
  55958. /**
  55959. * Returns the string "LineMesh"
  55960. */
  55961. LinesMesh.prototype.getClassName = function () {
  55962. return "LinesMesh";
  55963. };
  55964. Object.defineProperty(LinesMesh.prototype, "material", {
  55965. get: function () {
  55966. return this._colorShader;
  55967. },
  55968. set: function (value) {
  55969. // Do nothing
  55970. },
  55971. enumerable: true,
  55972. configurable: true
  55973. });
  55974. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  55975. get: function () {
  55976. return false;
  55977. },
  55978. enumerable: true,
  55979. configurable: true
  55980. });
  55981. LinesMesh.prototype.createInstance = function (name) {
  55982. throw new Error("LinesMeshes do not support createInstance.");
  55983. };
  55984. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  55985. if (!this._geometry) {
  55986. return this;
  55987. }
  55988. // VBOs
  55989. this._geometry._bind(this._colorShader.getEffect());
  55990. // Color
  55991. if (!this.useVertexColor) {
  55992. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  55993. }
  55994. return this;
  55995. };
  55996. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  55997. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  55998. return this;
  55999. }
  56000. var engine = this.getScene().getEngine();
  56001. // Draw order
  56002. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  56003. return this;
  56004. };
  56005. LinesMesh.prototype.dispose = function (doNotRecurse) {
  56006. this._colorShader.dispose();
  56007. _super.prototype.dispose.call(this, doNotRecurse);
  56008. };
  56009. /**
  56010. * Returns a new LineMesh object cloned from the current one.
  56011. */
  56012. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  56013. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  56014. };
  56015. return LinesMesh;
  56016. }(BABYLON.Mesh));
  56017. BABYLON.LinesMesh = LinesMesh;
  56018. })(BABYLON || (BABYLON = {}));
  56019. //# sourceMappingURL=babylon.linesMesh.js.map
  56020. var BABYLON;
  56021. (function (BABYLON) {
  56022. var MeshBuilder = /** @class */ (function () {
  56023. function MeshBuilder() {
  56024. }
  56025. MeshBuilder.updateSideOrientation = function (orientation) {
  56026. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  56027. return BABYLON.Mesh.DOUBLESIDE;
  56028. }
  56029. if (orientation === undefined || orientation === null) {
  56030. return BABYLON.Mesh.FRONTSIDE;
  56031. }
  56032. return orientation;
  56033. };
  56034. /**
  56035. * Creates a box mesh.
  56036. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  56037. * The parameter `size` sets the size (float) of each box side (default 1).
  56038. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  56039. * 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).
  56040. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  56041. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56042. * 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).
  56043. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56044. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56045. */
  56046. MeshBuilder.CreateBox = function (name, options, scene) {
  56047. if (scene === void 0) { scene = null; }
  56048. var box = new BABYLON.Mesh(name, scene);
  56049. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56050. box._originalBuilderSideOrientation = options.sideOrientation;
  56051. var vertexData = BABYLON.VertexData.CreateBox(options);
  56052. vertexData.applyToMesh(box, options.updatable);
  56053. return box;
  56054. };
  56055. /**
  56056. * Creates a sphere mesh.
  56057. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  56058. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  56059. * 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`).
  56060. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  56061. * 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
  56062. * 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).
  56063. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56064. * 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).
  56065. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56066. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56067. */
  56068. MeshBuilder.CreateSphere = function (name, options, scene) {
  56069. var sphere = new BABYLON.Mesh(name, scene);
  56070. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56071. sphere._originalBuilderSideOrientation = options.sideOrientation;
  56072. var vertexData = BABYLON.VertexData.CreateSphere(options);
  56073. vertexData.applyToMesh(sphere, options.updatable);
  56074. return sphere;
  56075. };
  56076. /**
  56077. * Creates a plane polygonal mesh. By default, this is a disc.
  56078. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  56079. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  56080. * 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.
  56081. * 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
  56082. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56083. * 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).
  56084. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56085. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56086. */
  56087. MeshBuilder.CreateDisc = function (name, options, scene) {
  56088. if (scene === void 0) { scene = null; }
  56089. var disc = new BABYLON.Mesh(name, scene);
  56090. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56091. disc._originalBuilderSideOrientation = options.sideOrientation;
  56092. var vertexData = BABYLON.VertexData.CreateDisc(options);
  56093. vertexData.applyToMesh(disc, options.updatable);
  56094. return disc;
  56095. };
  56096. /**
  56097. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  56098. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  56099. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  56100. * 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`).
  56101. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  56102. * 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.
  56103. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56104. * 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).
  56105. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56106. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56107. */
  56108. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  56109. var sphere = new BABYLON.Mesh(name, scene);
  56110. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56111. sphere._originalBuilderSideOrientation = options.sideOrientation;
  56112. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  56113. vertexData.applyToMesh(sphere, options.updatable);
  56114. return sphere;
  56115. };
  56116. ;
  56117. /**
  56118. * Creates a ribbon mesh.
  56119. * 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.
  56120. *
  56121. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  56122. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  56123. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  56124. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  56125. * 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.
  56126. * 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.
  56127. * 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
  56128. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56129. * 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).
  56130. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56131. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56132. * 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.
  56133. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  56134. * 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
  56135. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  56136. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  56137. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56138. */
  56139. MeshBuilder.CreateRibbon = function (name, options, scene) {
  56140. if (scene === void 0) { scene = null; }
  56141. var pathArray = options.pathArray;
  56142. var closeArray = options.closeArray;
  56143. var closePath = options.closePath;
  56144. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56145. var instance = options.instance;
  56146. var updatable = options.updatable;
  56147. if (instance) {
  56148. // positionFunction : ribbon case
  56149. // only pathArray and sideOrientation parameters are taken into account for positions update
  56150. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  56151. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  56152. var positionFunction = function (positions) {
  56153. var minlg = pathArray[0].length;
  56154. var i = 0;
  56155. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  56156. for (var si = 1; si <= ns; si++) {
  56157. for (var p = 0; p < pathArray.length; p++) {
  56158. var path = pathArray[p];
  56159. var l = path.length;
  56160. minlg = (minlg < l) ? minlg : l;
  56161. var j = 0;
  56162. while (j < minlg) {
  56163. positions[i] = path[j].x;
  56164. positions[i + 1] = path[j].y;
  56165. positions[i + 2] = path[j].z;
  56166. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  56167. BABYLON.Tmp.Vector3[0].x = path[j].x;
  56168. }
  56169. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  56170. BABYLON.Tmp.Vector3[1].x = path[j].x;
  56171. }
  56172. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  56173. BABYLON.Tmp.Vector3[0].y = path[j].y;
  56174. }
  56175. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  56176. BABYLON.Tmp.Vector3[1].y = path[j].y;
  56177. }
  56178. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  56179. BABYLON.Tmp.Vector3[0].z = path[j].z;
  56180. }
  56181. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  56182. BABYLON.Tmp.Vector3[1].z = path[j].z;
  56183. }
  56184. j++;
  56185. i += 3;
  56186. }
  56187. if (instance._closePath) {
  56188. positions[i] = path[0].x;
  56189. positions[i + 1] = path[0].y;
  56190. positions[i + 2] = path[0].z;
  56191. i += 3;
  56192. }
  56193. }
  56194. }
  56195. };
  56196. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56197. positionFunction(positions);
  56198. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  56199. instance._boundingInfo.update(instance._worldMatrix);
  56200. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  56201. if (options.colors) {
  56202. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56203. for (var c = 0; c < options.colors.length; c++) {
  56204. colors[c * 4] = options.colors[c].r;
  56205. colors[c * 4 + 1] = options.colors[c].g;
  56206. colors[c * 4 + 2] = options.colors[c].b;
  56207. colors[c * 4 + 3] = options.colors[c].a;
  56208. }
  56209. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  56210. }
  56211. if (options.uvs) {
  56212. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56213. for (var i = 0; i < options.uvs.length; i++) {
  56214. uvs[i * 2] = options.uvs[i].x;
  56215. uvs[i * 2 + 1] = options.uvs[i].y;
  56216. }
  56217. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  56218. }
  56219. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  56220. var indices = instance.getIndices();
  56221. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56222. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  56223. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  56224. if (instance._closePath) {
  56225. var indexFirst = 0;
  56226. var indexLast = 0;
  56227. for (var p = 0; p < pathArray.length; p++) {
  56228. indexFirst = instance._idx[p] * 3;
  56229. if (p + 1 < pathArray.length) {
  56230. indexLast = (instance._idx[p + 1] - 1) * 3;
  56231. }
  56232. else {
  56233. indexLast = normals.length - 3;
  56234. }
  56235. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  56236. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  56237. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  56238. normals[indexLast] = normals[indexFirst];
  56239. normals[indexLast + 1] = normals[indexFirst + 1];
  56240. normals[indexLast + 2] = normals[indexFirst + 2];
  56241. }
  56242. }
  56243. if (!(instance.areNormalsFrozen)) {
  56244. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  56245. }
  56246. }
  56247. return instance;
  56248. }
  56249. else {
  56250. var ribbon = new BABYLON.Mesh(name, scene);
  56251. ribbon._originalBuilderSideOrientation = sideOrientation;
  56252. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  56253. if (closePath) {
  56254. ribbon._idx = vertexData._idx;
  56255. }
  56256. ribbon._closePath = closePath;
  56257. ribbon._closeArray = closeArray;
  56258. vertexData.applyToMesh(ribbon, updatable);
  56259. return ribbon;
  56260. }
  56261. };
  56262. /**
  56263. * Creates a cylinder or a cone mesh.
  56264. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  56265. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  56266. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  56267. * 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.
  56268. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  56269. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  56270. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  56271. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  56272. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  56273. * 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).
  56274. * 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
  56275. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  56276. * 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
  56277. * 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.
  56278. * If `enclose` is false, a ring surface is one element.
  56279. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  56280. * 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
  56281. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56282. * 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).
  56283. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56284. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56285. */
  56286. MeshBuilder.CreateCylinder = function (name, options, scene) {
  56287. var cylinder = new BABYLON.Mesh(name, scene);
  56288. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56289. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  56290. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  56291. vertexData.applyToMesh(cylinder, options.updatable);
  56292. return cylinder;
  56293. };
  56294. /**
  56295. * Creates a torus mesh.
  56296. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  56297. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  56298. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  56299. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  56300. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56301. * 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).
  56302. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56303. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56304. */
  56305. MeshBuilder.CreateTorus = function (name, options, scene) {
  56306. var torus = new BABYLON.Mesh(name, scene);
  56307. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56308. torus._originalBuilderSideOrientation = options.sideOrientation;
  56309. var vertexData = BABYLON.VertexData.CreateTorus(options);
  56310. vertexData.applyToMesh(torus, options.updatable);
  56311. return torus;
  56312. };
  56313. /**
  56314. * Creates a torus knot mesh.
  56315. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  56316. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  56317. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  56318. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  56319. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  56320. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56321. * 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).
  56322. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56323. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56324. */
  56325. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  56326. var torusKnot = new BABYLON.Mesh(name, scene);
  56327. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56328. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  56329. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  56330. vertexData.applyToMesh(torusKnot, options.updatable);
  56331. return torusKnot;
  56332. };
  56333. /**
  56334. * Creates a line system mesh.
  56335. * A line system is a pool of many lines gathered in a single mesh.
  56336. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  56337. * 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.
  56338. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  56339. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  56340. * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter. The way to update it is the same than for
  56341. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  56342. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  56343. * 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
  56344. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  56345. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56346. */
  56347. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  56348. var instance = options.instance;
  56349. var lines = options.lines;
  56350. var colors = options.colors;
  56351. if (instance) {
  56352. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56353. var vertexColor;
  56354. var lineColors;
  56355. if (colors) {
  56356. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56357. }
  56358. var i = 0;
  56359. var c = 0;
  56360. for (var l = 0; l < lines.length; l++) {
  56361. var points = lines[l];
  56362. for (var p = 0; p < points.length; p++) {
  56363. positions[i] = points[p].x;
  56364. positions[i + 1] = points[p].y;
  56365. positions[i + 2] = points[p].z;
  56366. if (colors && vertexColor) {
  56367. lineColors = colors[l];
  56368. vertexColor[c] = lineColors[p].r;
  56369. vertexColor[c + 1] = lineColors[p].g;
  56370. vertexColor[c + 2] = lineColors[p].b;
  56371. vertexColor[c + 3] = lineColors[p].a;
  56372. c += 4;
  56373. }
  56374. i += 3;
  56375. }
  56376. }
  56377. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  56378. if (colors && vertexColor) {
  56379. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  56380. }
  56381. return instance;
  56382. }
  56383. // line system creation
  56384. var useVertexColor = (colors) ? true : false;
  56385. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  56386. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  56387. vertexData.applyToMesh(lineSystem, options.updatable);
  56388. return lineSystem;
  56389. };
  56390. /**
  56391. * Creates a line mesh.
  56392. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  56393. * 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.
  56394. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  56395. * The parameter `points` is an array successive Vector3.
  56396. * 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
  56397. * The optional parameter `colors` is an array of successive Color4, one per line point.
  56398. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  56399. * When updating an instance, remember that only point positions can change, not the number of points.
  56400. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56401. */
  56402. MeshBuilder.CreateLines = function (name, options, scene) {
  56403. if (scene === void 0) { scene = null; }
  56404. var colors = (options.colors) ? [options.colors] : null;
  56405. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  56406. return lines;
  56407. };
  56408. /**
  56409. * Creates a dashed line mesh.
  56410. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  56411. * 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.
  56412. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  56413. * The parameter `points` is an array successive Vector3.
  56414. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  56415. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  56416. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  56417. * 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
  56418. * When updating an instance, remember that only point positions can change, not the number of points.
  56419. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56420. */
  56421. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  56422. if (scene === void 0) { scene = null; }
  56423. var points = options.points;
  56424. var instance = options.instance;
  56425. var gapSize = options.gapSize || 1;
  56426. var dashSize = options.dashSize || 3;
  56427. if (instance) {
  56428. var positionFunction = function (positions) {
  56429. var curvect = BABYLON.Vector3.Zero();
  56430. var nbSeg = positions.length / 6;
  56431. var lg = 0;
  56432. var nb = 0;
  56433. var shft = 0;
  56434. var dashshft = 0;
  56435. var curshft = 0;
  56436. var p = 0;
  56437. var i = 0;
  56438. var j = 0;
  56439. for (i = 0; i < points.length - 1; i++) {
  56440. points[i + 1].subtractToRef(points[i], curvect);
  56441. lg += curvect.length();
  56442. }
  56443. shft = lg / nbSeg;
  56444. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  56445. for (i = 0; i < points.length - 1; i++) {
  56446. points[i + 1].subtractToRef(points[i], curvect);
  56447. nb = Math.floor(curvect.length() / shft);
  56448. curvect.normalize();
  56449. j = 0;
  56450. while (j < nb && p < positions.length) {
  56451. curshft = shft * j;
  56452. positions[p] = points[i].x + curshft * curvect.x;
  56453. positions[p + 1] = points[i].y + curshft * curvect.y;
  56454. positions[p + 2] = points[i].z + curshft * curvect.z;
  56455. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  56456. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  56457. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  56458. p += 6;
  56459. j++;
  56460. }
  56461. }
  56462. while (p < positions.length) {
  56463. positions[p] = points[i].x;
  56464. positions[p + 1] = points[i].y;
  56465. positions[p + 2] = points[i].z;
  56466. p += 3;
  56467. }
  56468. };
  56469. instance.updateMeshPositions(positionFunction, false);
  56470. return instance;
  56471. }
  56472. // dashed lines creation
  56473. var dashedLines = new BABYLON.LinesMesh(name, scene);
  56474. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  56475. vertexData.applyToMesh(dashedLines, options.updatable);
  56476. dashedLines.dashSize = dashSize;
  56477. dashedLines.gapSize = gapSize;
  56478. return dashedLines;
  56479. };
  56480. /**
  56481. * Creates an extruded shape mesh.
  56482. * 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.
  56483. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  56484. *
  56485. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56486. * 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
  56487. * extruded along the Z axis.
  56488. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56489. * 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.
  56490. * The parameter `scale` (float, default 1) is the value to scale the shape.
  56491. * 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
  56492. * 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
  56493. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  56494. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56495. * 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).
  56496. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56497. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56498. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56499. */
  56500. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  56501. if (scene === void 0) { scene = null; }
  56502. var path = options.path;
  56503. var shape = options.shape;
  56504. var scale = options.scale || 1;
  56505. var rotation = options.rotation || 0;
  56506. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56507. var updatable = options.updatable;
  56508. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56509. var instance = options.instance || null;
  56510. var invertUV = options.invertUV || false;
  56511. 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);
  56512. };
  56513. /**
  56514. * Creates an custom extruded shape mesh.
  56515. * 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.
  56516. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  56517. *
  56518. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56519. * 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
  56520. * extruded along the Z axis.
  56521. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56522. * 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
  56523. * and the distance of this point from the begining of the path :
  56524. * ```javascript
  56525. * var rotationFunction = function(i, distance) {
  56526. * // do things
  56527. * return rotationValue; }
  56528. * ```
  56529. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  56530. * 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
  56531. * and the distance of this point from the begining of the path :
  56532. * ```javascript
  56533. * var scaleFunction = function(i, distance) {
  56534. * // do things
  56535. * return scaleValue;}
  56536. * ```
  56537. * It must returns a float value that will be the scale value applied to the shape on each path point.
  56538. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  56539. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  56540. * 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
  56541. * 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
  56542. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  56543. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56544. * 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).
  56545. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56546. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56547. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56548. */
  56549. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  56550. var path = options.path;
  56551. var shape = options.shape;
  56552. var scaleFunction = options.scaleFunction || (function () { return 1; });
  56553. var rotationFunction = options.rotationFunction || (function () { return 0; });
  56554. var ribbonCloseArray = options.ribbonCloseArray || false;
  56555. var ribbonClosePath = options.ribbonClosePath || false;
  56556. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56557. var updatable = options.updatable;
  56558. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56559. var instance = options.instance;
  56560. var invertUV = options.invertUV || false;
  56561. 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);
  56562. };
  56563. /**
  56564. * Creates lathe mesh.
  56565. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  56566. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  56567. *
  56568. * 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
  56569. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  56570. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  56571. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  56572. * 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.
  56573. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  56574. * 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
  56575. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56576. * 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).
  56577. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56578. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56579. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56580. */
  56581. MeshBuilder.CreateLathe = function (name, options, scene) {
  56582. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  56583. var closed = (options.closed === undefined) ? true : options.closed;
  56584. var shape = options.shape;
  56585. var radius = options.radius || 1;
  56586. var tessellation = options.tessellation || 64;
  56587. var updatable = options.updatable;
  56588. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56589. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  56590. var pi2 = Math.PI * 2;
  56591. var paths = new Array();
  56592. var invertUV = options.invertUV || false;
  56593. var i = 0;
  56594. var p = 0;
  56595. var step = pi2 / tessellation * arc;
  56596. var rotated;
  56597. var path = new Array();
  56598. ;
  56599. for (i = 0; i <= tessellation; i++) {
  56600. var path = [];
  56601. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  56602. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  56603. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  56604. }
  56605. for (p = 0; p < shape.length; p++) {
  56606. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  56607. path.push(rotated);
  56608. }
  56609. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  56610. 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));
  56611. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  56612. }
  56613. paths.push(path);
  56614. }
  56615. // lathe ribbon
  56616. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  56617. return lathe;
  56618. };
  56619. /**
  56620. * Creates a plane mesh.
  56621. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  56622. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  56623. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  56624. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  56625. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56626. * 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).
  56627. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56628. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56629. */
  56630. MeshBuilder.CreatePlane = function (name, options, scene) {
  56631. var plane = new BABYLON.Mesh(name, scene);
  56632. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56633. plane._originalBuilderSideOrientation = options.sideOrientation;
  56634. var vertexData = BABYLON.VertexData.CreatePlane(options);
  56635. vertexData.applyToMesh(plane, options.updatable);
  56636. if (options.sourcePlane) {
  56637. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  56638. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  56639. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  56640. plane.rotate(vectorProduct, product);
  56641. }
  56642. return plane;
  56643. };
  56644. /**
  56645. * Creates a ground mesh.
  56646. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  56647. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  56648. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  56649. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56650. */
  56651. MeshBuilder.CreateGround = function (name, options, scene) {
  56652. var ground = new BABYLON.GroundMesh(name, scene);
  56653. ground._setReady(false);
  56654. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  56655. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  56656. ground._width = options.width || 1;
  56657. ground._height = options.height || 1;
  56658. ground._maxX = ground._width / 2;
  56659. ground._maxZ = ground._height / 2;
  56660. ground._minX = -ground._maxX;
  56661. ground._minZ = -ground._maxZ;
  56662. var vertexData = BABYLON.VertexData.CreateGround(options);
  56663. vertexData.applyToMesh(ground, options.updatable);
  56664. ground._setReady(true);
  56665. return ground;
  56666. };
  56667. /**
  56668. * Creates a tiled ground mesh.
  56669. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  56670. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  56671. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  56672. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  56673. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  56674. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  56675. * numbers of subdivisions on the ground width and height of each tile.
  56676. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56677. */
  56678. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  56679. var tiledGround = new BABYLON.Mesh(name, scene);
  56680. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  56681. vertexData.applyToMesh(tiledGround, options.updatable);
  56682. return tiledGround;
  56683. };
  56684. /**
  56685. * Creates a ground mesh from a height map.
  56686. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  56687. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  56688. * The parameter `url` sets the URL of the height map image resource.
  56689. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  56690. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  56691. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  56692. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  56693. * 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.
  56694. * 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).
  56695. * This function is passed the newly built mesh :
  56696. * ```javascript
  56697. * function(mesh) { // do things
  56698. * return; }
  56699. * ```
  56700. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56701. */
  56702. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  56703. var width = options.width || 10.0;
  56704. var height = options.height || 10.0;
  56705. var subdivisions = options.subdivisions || 1 | 0;
  56706. var minHeight = options.minHeight || 0.0;
  56707. var maxHeight = options.maxHeight || 1.0;
  56708. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  56709. var updatable = options.updatable;
  56710. var onReady = options.onReady;
  56711. var ground = new BABYLON.GroundMesh(name, scene);
  56712. ground._subdivisionsX = subdivisions;
  56713. ground._subdivisionsY = subdivisions;
  56714. ground._width = width;
  56715. ground._height = height;
  56716. ground._maxX = ground._width / 2.0;
  56717. ground._maxZ = ground._height / 2.0;
  56718. ground._minX = -ground._maxX;
  56719. ground._minZ = -ground._maxZ;
  56720. ground._setReady(false);
  56721. var onload = function (img) {
  56722. // Getting height map data
  56723. var canvas = document.createElement("canvas");
  56724. var context = canvas.getContext("2d");
  56725. if (!context) {
  56726. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  56727. }
  56728. if (scene.isDisposed) {
  56729. return;
  56730. }
  56731. var bufferWidth = img.width;
  56732. var bufferHeight = img.height;
  56733. canvas.width = bufferWidth;
  56734. canvas.height = bufferHeight;
  56735. context.drawImage(img, 0, 0);
  56736. // Create VertexData from map data
  56737. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  56738. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  56739. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  56740. width: width, height: height,
  56741. subdivisions: subdivisions,
  56742. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  56743. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  56744. });
  56745. vertexData.applyToMesh(ground, updatable);
  56746. //execute ready callback, if set
  56747. if (onReady) {
  56748. onReady(ground);
  56749. }
  56750. ground._setReady(true);
  56751. };
  56752. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  56753. return ground;
  56754. };
  56755. /**
  56756. * Creates a polygon mesh.
  56757. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  56758. * 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.
  56759. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56760. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56761. * 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).
  56762. * Remember you can only change the shape positions, not their number when updating a polygon.
  56763. */
  56764. MeshBuilder.CreatePolygon = function (name, options, scene) {
  56765. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56766. var shape = options.shape;
  56767. var holes = options.holes || [];
  56768. var depth = options.depth || 0;
  56769. var contours = [];
  56770. var hole = [];
  56771. for (var i = 0; i < shape.length; i++) {
  56772. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  56773. }
  56774. var epsilon = 0.00000001;
  56775. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  56776. contours.pop();
  56777. }
  56778. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  56779. for (var hNb = 0; hNb < holes.length; hNb++) {
  56780. hole = [];
  56781. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  56782. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  56783. }
  56784. polygonTriangulation.addHole(hole);
  56785. }
  56786. var polygon = polygonTriangulation.build(options.updatable, depth);
  56787. polygon._originalBuilderSideOrientation = options.sideOrientation;
  56788. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  56789. vertexData.applyToMesh(polygon, options.updatable);
  56790. return polygon;
  56791. };
  56792. ;
  56793. /**
  56794. * Creates an extruded polygon mesh, with depth in the Y direction.
  56795. * 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).
  56796. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  56797. */
  56798. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  56799. return MeshBuilder.CreatePolygon(name, options, scene);
  56800. };
  56801. ;
  56802. /**
  56803. * Creates a tube mesh.
  56804. * 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.
  56805. *
  56806. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  56807. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  56808. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  56809. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  56810. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  56811. * 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.
  56812. * It must return a radius value (positive float) :
  56813. * ```javascript
  56814. * var radiusFunction = function(i, distance) {
  56815. * // do things
  56816. * return radius; }
  56817. * ```
  56818. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  56819. * 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
  56820. * 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
  56821. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56822. * 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).
  56823. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56824. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56825. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56826. */
  56827. MeshBuilder.CreateTube = function (name, options, scene) {
  56828. var path = options.path;
  56829. var instance = options.instance;
  56830. var radius = 1.0;
  56831. if (instance) {
  56832. radius = instance.radius;
  56833. }
  56834. if (options.radius !== undefined) {
  56835. radius = options.radius;
  56836. }
  56837. ;
  56838. var tessellation = options.tessellation || 64 | 0;
  56839. var radiusFunction = options.radiusFunction || null;
  56840. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  56841. var invertUV = options.invertUV || false;
  56842. var updatable = options.updatable;
  56843. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56844. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  56845. // tube geometry
  56846. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  56847. var tangents = path3D.getTangents();
  56848. var normals = path3D.getNormals();
  56849. var distances = path3D.getDistances();
  56850. var pi2 = Math.PI * 2;
  56851. var step = pi2 / tessellation * arc;
  56852. var returnRadius = function () { return radius; };
  56853. var radiusFunctionFinal = radiusFunction || returnRadius;
  56854. var circlePath;
  56855. var rad;
  56856. var normal;
  56857. var rotated;
  56858. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  56859. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  56860. for (var i = 0; i < path.length; i++) {
  56861. rad = radiusFunctionFinal(i, distances[i]); // current radius
  56862. circlePath = Array(); // current circle array
  56863. normal = normals[i]; // current normal
  56864. for (var t = 0; t < tessellation; t++) {
  56865. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  56866. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  56867. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  56868. rotated.scaleInPlace(rad).addInPlace(path[i]);
  56869. circlePath[t] = rotated;
  56870. }
  56871. circlePaths[index] = circlePath;
  56872. index++;
  56873. }
  56874. // cap
  56875. var capPath = function (nbPoints, pathIndex) {
  56876. var pointCap = Array();
  56877. for (var i = 0; i < nbPoints; i++) {
  56878. pointCap.push(path[pathIndex]);
  56879. }
  56880. return pointCap;
  56881. };
  56882. switch (cap) {
  56883. case BABYLON.Mesh.NO_CAP:
  56884. break;
  56885. case BABYLON.Mesh.CAP_START:
  56886. circlePaths[0] = capPath(tessellation, 0);
  56887. circlePaths[1] = circlePaths[2].slice(0);
  56888. break;
  56889. case BABYLON.Mesh.CAP_END:
  56890. circlePaths[index] = circlePaths[index - 1].slice(0);
  56891. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  56892. break;
  56893. case BABYLON.Mesh.CAP_ALL:
  56894. circlePaths[0] = capPath(tessellation, 0);
  56895. circlePaths[1] = circlePaths[2].slice(0);
  56896. circlePaths[index] = circlePaths[index - 1].slice(0);
  56897. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  56898. break;
  56899. default:
  56900. break;
  56901. }
  56902. return circlePaths;
  56903. };
  56904. var path3D;
  56905. var pathArray;
  56906. if (instance) {
  56907. var arc = options.arc || instance.arc;
  56908. path3D = (instance.path3D).update(path);
  56909. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  56910. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  56911. instance.path3D = path3D;
  56912. instance.pathArray = pathArray;
  56913. instance.arc = arc;
  56914. instance.radius = radius;
  56915. return instance;
  56916. }
  56917. // tube creation
  56918. path3D = new BABYLON.Path3D(path);
  56919. var newPathArray = new Array();
  56920. cap = (cap < 0 || cap > 3) ? 0 : cap;
  56921. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  56922. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  56923. tube.pathArray = pathArray;
  56924. tube.path3D = path3D;
  56925. tube.tessellation = tessellation;
  56926. tube.cap = cap;
  56927. tube.arc = options.arc;
  56928. tube.radius = radius;
  56929. return tube;
  56930. };
  56931. /**
  56932. * Creates a polyhedron mesh.
  56933. *
  56934. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  56935. * 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
  56936. * to choose the wanted type.
  56937. * The parameter `size` (positive float, default 1) sets the polygon size.
  56938. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  56939. * 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`.
  56940. * 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
  56941. * 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)`).
  56942. * 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
  56943. * 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.
  56944. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56945. * 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).
  56946. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56947. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56948. */
  56949. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  56950. var polyhedron = new BABYLON.Mesh(name, scene);
  56951. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56952. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  56953. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  56954. vertexData.applyToMesh(polyhedron, options.updatable);
  56955. return polyhedron;
  56956. };
  56957. /**
  56958. * Creates a decal mesh.
  56959. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  56960. * 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.
  56961. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  56962. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  56963. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  56964. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  56965. */
  56966. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  56967. var indices = sourceMesh.getIndices();
  56968. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56969. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56970. var position = options.position || BABYLON.Vector3.Zero();
  56971. var normal = options.normal || BABYLON.Vector3.Up();
  56972. var size = options.size || BABYLON.Vector3.One();
  56973. var angle = options.angle || 0;
  56974. // Getting correct rotation
  56975. if (!normal) {
  56976. var target = new BABYLON.Vector3(0, 0, 1);
  56977. var camera = sourceMesh.getScene().activeCamera;
  56978. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  56979. normal = camera.globalPosition.subtract(cameraWorldTarget);
  56980. }
  56981. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  56982. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  56983. var pitch = Math.atan2(normal.y, len);
  56984. // Matrix
  56985. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  56986. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  56987. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  56988. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  56989. var vertexData = new BABYLON.VertexData();
  56990. vertexData.indices = [];
  56991. vertexData.positions = [];
  56992. vertexData.normals = [];
  56993. vertexData.uvs = [];
  56994. var currentVertexDataIndex = 0;
  56995. var extractDecalVector3 = function (indexId) {
  56996. var result = new BABYLON.PositionNormalVertex();
  56997. if (!indices || !positions || !normals) {
  56998. return result;
  56999. }
  57000. var vertexId = indices[indexId];
  57001. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  57002. // Send vector to decal local world
  57003. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  57004. // Get normal
  57005. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  57006. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  57007. return result;
  57008. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  57009. var clip = function (vertices, axis) {
  57010. if (vertices.length === 0) {
  57011. return vertices;
  57012. }
  57013. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  57014. var clipVertices = function (v0, v1) {
  57015. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  57016. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  57017. };
  57018. var result = new Array();
  57019. for (var index = 0; index < vertices.length; index += 3) {
  57020. var v1Out;
  57021. var v2Out;
  57022. var v3Out;
  57023. var total = 0;
  57024. var nV1 = null;
  57025. var nV2 = null;
  57026. var nV3 = null;
  57027. var nV4 = null;
  57028. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  57029. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  57030. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  57031. v1Out = d1 > 0;
  57032. v2Out = d2 > 0;
  57033. v3Out = d3 > 0;
  57034. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  57035. switch (total) {
  57036. case 0:
  57037. result.push(vertices[index]);
  57038. result.push(vertices[index + 1]);
  57039. result.push(vertices[index + 2]);
  57040. break;
  57041. case 1:
  57042. if (v1Out) {
  57043. nV1 = vertices[index + 1];
  57044. nV2 = vertices[index + 2];
  57045. nV3 = clipVertices(vertices[index], nV1);
  57046. nV4 = clipVertices(vertices[index], nV2);
  57047. }
  57048. if (v2Out) {
  57049. nV1 = vertices[index];
  57050. nV2 = vertices[index + 2];
  57051. nV3 = clipVertices(vertices[index + 1], nV1);
  57052. nV4 = clipVertices(vertices[index + 1], nV2);
  57053. result.push(nV3);
  57054. result.push(nV2.clone());
  57055. result.push(nV1.clone());
  57056. result.push(nV2.clone());
  57057. result.push(nV3.clone());
  57058. result.push(nV4);
  57059. break;
  57060. }
  57061. if (v3Out) {
  57062. nV1 = vertices[index];
  57063. nV2 = vertices[index + 1];
  57064. nV3 = clipVertices(vertices[index + 2], nV1);
  57065. nV4 = clipVertices(vertices[index + 2], nV2);
  57066. }
  57067. if (nV1 && nV2 && nV3 && nV4) {
  57068. result.push(nV1.clone());
  57069. result.push(nV2.clone());
  57070. result.push(nV3);
  57071. result.push(nV4);
  57072. result.push(nV3.clone());
  57073. result.push(nV2.clone());
  57074. }
  57075. break;
  57076. case 2:
  57077. if (!v1Out) {
  57078. nV1 = vertices[index].clone();
  57079. nV2 = clipVertices(nV1, vertices[index + 1]);
  57080. nV3 = clipVertices(nV1, vertices[index + 2]);
  57081. result.push(nV1);
  57082. result.push(nV2);
  57083. result.push(nV3);
  57084. }
  57085. if (!v2Out) {
  57086. nV1 = vertices[index + 1].clone();
  57087. nV2 = clipVertices(nV1, vertices[index + 2]);
  57088. nV3 = clipVertices(nV1, vertices[index]);
  57089. result.push(nV1);
  57090. result.push(nV2);
  57091. result.push(nV3);
  57092. }
  57093. if (!v3Out) {
  57094. nV1 = vertices[index + 2].clone();
  57095. nV2 = clipVertices(nV1, vertices[index]);
  57096. nV3 = clipVertices(nV1, vertices[index + 1]);
  57097. result.push(nV1);
  57098. result.push(nV2);
  57099. result.push(nV3);
  57100. }
  57101. break;
  57102. case 3:
  57103. break;
  57104. }
  57105. }
  57106. return result;
  57107. };
  57108. for (var index = 0; index < indices.length; index += 3) {
  57109. var faceVertices = new Array();
  57110. faceVertices.push(extractDecalVector3(index));
  57111. faceVertices.push(extractDecalVector3(index + 1));
  57112. faceVertices.push(extractDecalVector3(index + 2));
  57113. // Clip
  57114. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  57115. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  57116. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  57117. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  57118. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  57119. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  57120. if (faceVertices.length === 0) {
  57121. continue;
  57122. }
  57123. // Add UVs and get back to world
  57124. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  57125. var vertex = faceVertices[vIndex];
  57126. //TODO check for Int32Array | Uint32Array | Uint16Array
  57127. vertexData.indices.push(currentVertexDataIndex);
  57128. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  57129. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  57130. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  57131. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  57132. currentVertexDataIndex++;
  57133. }
  57134. }
  57135. // Return mesh
  57136. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  57137. vertexData.applyToMesh(decal);
  57138. decal.position = position.clone();
  57139. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  57140. return decal;
  57141. };
  57142. // Privates
  57143. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  57144. // extrusion geometry
  57145. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  57146. var tangents = path3D.getTangents();
  57147. var normals = path3D.getNormals();
  57148. var binormals = path3D.getBinormals();
  57149. var distances = path3D.getDistances();
  57150. var angle = 0;
  57151. var returnScale = function () { return scale !== null ? scale : 1; };
  57152. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  57153. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  57154. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  57155. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  57156. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  57157. for (var i = 0; i < curve.length; i++) {
  57158. var shapePath = new Array();
  57159. var angleStep = rotate(i, distances[i]);
  57160. var scaleRatio = scl(i, distances[i]);
  57161. for (var p = 0; p < shape.length; p++) {
  57162. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  57163. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  57164. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  57165. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  57166. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  57167. shapePath[p] = rotated;
  57168. }
  57169. shapePaths[index] = shapePath;
  57170. angle += angleStep;
  57171. index++;
  57172. }
  57173. // cap
  57174. var capPath = function (shapePath) {
  57175. var pointCap = Array();
  57176. var barycenter = BABYLON.Vector3.Zero();
  57177. var i;
  57178. for (i = 0; i < shapePath.length; i++) {
  57179. barycenter.addInPlace(shapePath[i]);
  57180. }
  57181. barycenter.scaleInPlace(1.0 / shapePath.length);
  57182. for (i = 0; i < shapePath.length; i++) {
  57183. pointCap.push(barycenter);
  57184. }
  57185. return pointCap;
  57186. };
  57187. switch (cap) {
  57188. case BABYLON.Mesh.NO_CAP:
  57189. break;
  57190. case BABYLON.Mesh.CAP_START:
  57191. shapePaths[0] = capPath(shapePaths[2]);
  57192. shapePaths[1] = shapePaths[2];
  57193. break;
  57194. case BABYLON.Mesh.CAP_END:
  57195. shapePaths[index] = shapePaths[index - 1];
  57196. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  57197. break;
  57198. case BABYLON.Mesh.CAP_ALL:
  57199. shapePaths[0] = capPath(shapePaths[2]);
  57200. shapePaths[1] = shapePaths[2];
  57201. shapePaths[index] = shapePaths[index - 1];
  57202. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  57203. break;
  57204. default:
  57205. break;
  57206. }
  57207. return shapePaths;
  57208. };
  57209. var path3D;
  57210. var pathArray;
  57211. if (instance) {
  57212. path3D = (instance.path3D).update(curve);
  57213. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  57214. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  57215. return instance;
  57216. }
  57217. // extruded shape creation
  57218. path3D = new BABYLON.Path3D(curve);
  57219. var newShapePaths = new Array();
  57220. cap = (cap < 0 || cap > 3) ? 0 : cap;
  57221. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  57222. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  57223. extrudedGeneric.pathArray = pathArray;
  57224. extrudedGeneric.path3D = path3D;
  57225. extrudedGeneric.cap = cap;
  57226. return extrudedGeneric;
  57227. };
  57228. return MeshBuilder;
  57229. }());
  57230. BABYLON.MeshBuilder = MeshBuilder;
  57231. })(BABYLON || (BABYLON = {}));
  57232. //# sourceMappingURL=babylon.meshBuilder.js.map
  57233. var BABYLON;
  57234. (function (BABYLON) {
  57235. /**
  57236. * Draco compression (https://google.github.io/draco/)
  57237. */
  57238. var DracoCompression = /** @class */ (function () {
  57239. /**
  57240. * Constructor
  57241. * @param numWorkers The number of workers for async operations
  57242. */
  57243. function DracoCompression(numWorkers) {
  57244. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  57245. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  57246. if (!workerBlobUrl || !Worker) {
  57247. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  57248. return;
  57249. }
  57250. var workers = new Array(numWorkers);
  57251. for (var i = 0; i < workers.length; i++) {
  57252. var worker = new Worker(workerBlobUrl);
  57253. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  57254. workers[i] = worker;
  57255. }
  57256. this._workerPool = new BABYLON.WorkerPool(workers);
  57257. }
  57258. /**
  57259. * Stop all async operations and release resources.
  57260. */
  57261. DracoCompression.prototype.dispose = function () {
  57262. this._workerPool.dispose();
  57263. delete this._workerPool;
  57264. };
  57265. /**
  57266. * Decode Draco compressed mesh data to vertex data.
  57267. * @param data The array buffer view for the Draco compression data
  57268. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  57269. * @returns A promise that resolves with the decoded vertex data
  57270. */
  57271. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  57272. var _this = this;
  57273. return new Promise(function (resolve, reject) {
  57274. _this._workerPool.push(function (worker, onComplete) {
  57275. var vertexData = new BABYLON.VertexData();
  57276. var onError = function (error) {
  57277. worker.removeEventListener("error", onError);
  57278. worker.removeEventListener("message", onMessage);
  57279. reject(error);
  57280. onComplete();
  57281. };
  57282. var onMessage = function (message) {
  57283. if (message.data === "done") {
  57284. worker.removeEventListener("error", onError);
  57285. worker.removeEventListener("message", onMessage);
  57286. resolve(vertexData);
  57287. onComplete();
  57288. }
  57289. else if (message.data.id === "indices") {
  57290. vertexData.indices = message.data.value;
  57291. }
  57292. else {
  57293. vertexData.set(message.data.value, message.data.id);
  57294. }
  57295. };
  57296. worker.addEventListener("error", onError);
  57297. worker.addEventListener("message", onMessage);
  57298. var dataCopy = new Uint8Array(data.byteLength);
  57299. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  57300. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  57301. });
  57302. });
  57303. };
  57304. /**
  57305. * The worker function that gets converted to a blob url to pass into a worker.
  57306. */
  57307. DracoCompression._Worker = function () {
  57308. // self is actually a DedicatedWorkerGlobalScope
  57309. var _self = self;
  57310. var decodeMesh = function (data, attributes) {
  57311. var dracoModule = new DracoDecoderModule();
  57312. var buffer = new dracoModule.DecoderBuffer();
  57313. buffer.Init(data, data.byteLength);
  57314. var decoder = new dracoModule.Decoder();
  57315. var geometry;
  57316. var status;
  57317. try {
  57318. var type = decoder.GetEncodedGeometryType(buffer);
  57319. switch (type) {
  57320. case dracoModule.TRIANGULAR_MESH:
  57321. geometry = new dracoModule.Mesh();
  57322. status = decoder.DecodeBufferToMesh(buffer, geometry);
  57323. break;
  57324. case dracoModule.POINT_CLOUD:
  57325. geometry = new dracoModule.PointCloud();
  57326. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  57327. break;
  57328. default:
  57329. throw new Error("Invalid geometry type " + type);
  57330. }
  57331. if (!status.ok() || !geometry.ptr) {
  57332. throw new Error(status.error_msg());
  57333. }
  57334. var numPoints = geometry.num_points();
  57335. if (type === dracoModule.TRIANGULAR_MESH) {
  57336. var numFaces = geometry.num_faces();
  57337. var faceIndices = new dracoModule.DracoInt32Array();
  57338. try {
  57339. var indices = new Uint32Array(numFaces * 3);
  57340. for (var i = 0; i < numFaces; i++) {
  57341. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  57342. var offset = i * 3;
  57343. indices[offset + 0] = faceIndices.GetValue(0);
  57344. indices[offset + 1] = faceIndices.GetValue(1);
  57345. indices[offset + 2] = faceIndices.GetValue(2);
  57346. }
  57347. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  57348. }
  57349. finally {
  57350. dracoModule.destroy(faceIndices);
  57351. }
  57352. }
  57353. for (var kind in attributes) {
  57354. var uniqueId = attributes[kind];
  57355. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  57356. var dracoData = new dracoModule.DracoFloat32Array();
  57357. try {
  57358. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  57359. var babylonData = new Float32Array(numPoints * attribute.num_components());
  57360. for (var i = 0; i < babylonData.length; i++) {
  57361. babylonData[i] = dracoData.GetValue(i);
  57362. }
  57363. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  57364. }
  57365. finally {
  57366. dracoModule.destroy(dracoData);
  57367. }
  57368. }
  57369. }
  57370. finally {
  57371. if (geometry) {
  57372. dracoModule.destroy(geometry);
  57373. }
  57374. dracoModule.destroy(decoder);
  57375. dracoModule.destroy(buffer);
  57376. }
  57377. _self.postMessage("done");
  57378. };
  57379. _self.onmessage = function (event) {
  57380. switch (event.data.id) {
  57381. case "initDecoder": {
  57382. importScripts(event.data.url);
  57383. break;
  57384. }
  57385. case "decodeMesh": {
  57386. decodeMesh(event.data.data, event.data.attributes);
  57387. break;
  57388. }
  57389. }
  57390. };
  57391. };
  57392. DracoCompression._GetDefaultDecoderUrl = function () {
  57393. if (!BABYLON.Tools.IsWindowObjectExist) {
  57394. return null;
  57395. }
  57396. for (var i = 0; i < document.scripts.length; i++) {
  57397. if (document.scripts[i].type === "text/x-draco-decoder") {
  57398. return document.scripts[i].src;
  57399. }
  57400. }
  57401. return null;
  57402. };
  57403. /**
  57404. * Gets the url to the draco decoder if available.
  57405. */
  57406. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  57407. return DracoCompression;
  57408. }());
  57409. BABYLON.DracoCompression = DracoCompression;
  57410. })(BABYLON || (BABYLON = {}));
  57411. //# sourceMappingURL=babylon.dracoCompression.js.map
  57412. var BABYLON;
  57413. (function (BABYLON) {
  57414. var AudioEngine = /** @class */ (function () {
  57415. function AudioEngine() {
  57416. this._audioContext = null;
  57417. this._audioContextInitialized = false;
  57418. this.canUseWebAudio = false;
  57419. this.WarnedWebAudioUnsupported = false;
  57420. this.unlocked = false;
  57421. this.isMP3supported = false;
  57422. this.isOGGsupported = false;
  57423. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  57424. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  57425. this.canUseWebAudio = true;
  57426. }
  57427. var audioElem = document.createElement('audio');
  57428. try {
  57429. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  57430. this.isMP3supported = true;
  57431. }
  57432. }
  57433. catch (e) {
  57434. // protect error during capability check.
  57435. }
  57436. try {
  57437. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  57438. this.isOGGsupported = true;
  57439. }
  57440. }
  57441. catch (e) {
  57442. // protect error during capability check.
  57443. }
  57444. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  57445. this._unlockiOSaudio();
  57446. }
  57447. else {
  57448. this.unlocked = true;
  57449. }
  57450. }
  57451. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  57452. get: function () {
  57453. if (!this._audioContextInitialized) {
  57454. this._initializeAudioContext();
  57455. }
  57456. return this._audioContext;
  57457. },
  57458. enumerable: true,
  57459. configurable: true
  57460. });
  57461. AudioEngine.prototype._unlockiOSaudio = function () {
  57462. var _this = this;
  57463. var unlockaudio = function () {
  57464. if (!_this.audioContext) {
  57465. return;
  57466. }
  57467. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  57468. var source = _this.audioContext.createBufferSource();
  57469. source.buffer = buffer;
  57470. source.connect(_this.audioContext.destination);
  57471. source.start(0);
  57472. setTimeout(function () {
  57473. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  57474. _this.unlocked = true;
  57475. window.removeEventListener('touchend', unlockaudio, false);
  57476. if (_this.onAudioUnlocked) {
  57477. _this.onAudioUnlocked();
  57478. }
  57479. }
  57480. }, 0);
  57481. };
  57482. window.addEventListener('touchend', unlockaudio, false);
  57483. };
  57484. AudioEngine.prototype._initializeAudioContext = function () {
  57485. try {
  57486. if (this.canUseWebAudio) {
  57487. this._audioContext = new AudioContext();
  57488. // create a global volume gain node
  57489. this.masterGain = this._audioContext.createGain();
  57490. this.masterGain.gain.value = 1;
  57491. this.masterGain.connect(this._audioContext.destination);
  57492. this._audioContextInitialized = true;
  57493. }
  57494. }
  57495. catch (e) {
  57496. this.canUseWebAudio = false;
  57497. BABYLON.Tools.Error("Web Audio: " + e.message);
  57498. }
  57499. };
  57500. AudioEngine.prototype.dispose = function () {
  57501. if (this.canUseWebAudio && this._audioContextInitialized) {
  57502. if (this._connectedAnalyser && this._audioContext) {
  57503. this._connectedAnalyser.stopDebugCanvas();
  57504. this._connectedAnalyser.dispose();
  57505. this.masterGain.disconnect();
  57506. this.masterGain.connect(this._audioContext.destination);
  57507. this._connectedAnalyser = null;
  57508. }
  57509. this.masterGain.gain.value = 1;
  57510. }
  57511. this.WarnedWebAudioUnsupported = false;
  57512. };
  57513. AudioEngine.prototype.getGlobalVolume = function () {
  57514. if (this.canUseWebAudio && this._audioContextInitialized) {
  57515. return this.masterGain.gain.value;
  57516. }
  57517. else {
  57518. return -1;
  57519. }
  57520. };
  57521. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  57522. if (this.canUseWebAudio && this._audioContextInitialized) {
  57523. this.masterGain.gain.value = newVolume;
  57524. }
  57525. };
  57526. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  57527. if (this._connectedAnalyser) {
  57528. this._connectedAnalyser.stopDebugCanvas();
  57529. }
  57530. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  57531. this._connectedAnalyser = analyser;
  57532. this.masterGain.disconnect();
  57533. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  57534. }
  57535. };
  57536. return AudioEngine;
  57537. }());
  57538. BABYLON.AudioEngine = AudioEngine;
  57539. })(BABYLON || (BABYLON = {}));
  57540. //# sourceMappingURL=babylon.audioEngine.js.map
  57541. var BABYLON;
  57542. (function (BABYLON) {
  57543. var Sound = /** @class */ (function () {
  57544. /**
  57545. * Create a sound and attach it to a scene
  57546. * @param name Name of your sound
  57547. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  57548. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  57549. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  57550. */
  57551. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  57552. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  57553. var _this = this;
  57554. this.autoplay = false;
  57555. this.loop = false;
  57556. this.useCustomAttenuation = false;
  57557. this.spatialSound = false;
  57558. this.refDistance = 1;
  57559. this.rolloffFactor = 1;
  57560. this.maxDistance = 100;
  57561. this.distanceModel = "linear";
  57562. this._panningModel = "equalpower";
  57563. this._playbackRate = 1;
  57564. this._streaming = false;
  57565. this._startTime = 0;
  57566. this._startOffset = 0;
  57567. this._position = BABYLON.Vector3.Zero();
  57568. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  57569. this._volume = 1;
  57570. this._isReadyToPlay = false;
  57571. this.isPlaying = false;
  57572. this.isPaused = false;
  57573. this._isDirectional = false;
  57574. // Used if you'd like to create a directional sound.
  57575. // If not set, the sound will be omnidirectional
  57576. this._coneInnerAngle = 360;
  57577. this._coneOuterAngle = 360;
  57578. this._coneOuterGain = 0;
  57579. this._isOutputConnected = false;
  57580. this._urlType = "Unknown";
  57581. this.name = name;
  57582. this._scene = scene;
  57583. this._readyToPlayCallback = readyToPlayCallback;
  57584. // Default custom attenuation function is a linear attenuation
  57585. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  57586. if (currentDistance < maxDistance) {
  57587. return currentVolume * (1 - currentDistance / maxDistance);
  57588. }
  57589. else {
  57590. return 0;
  57591. }
  57592. };
  57593. if (options) {
  57594. this.autoplay = options.autoplay || false;
  57595. this.loop = options.loop || false;
  57596. // if volume === 0, we need another way to check this option
  57597. if (options.volume !== undefined) {
  57598. this._volume = options.volume;
  57599. }
  57600. this.spatialSound = options.spatialSound || false;
  57601. this.maxDistance = options.maxDistance || 100;
  57602. this.useCustomAttenuation = options.useCustomAttenuation || false;
  57603. this.rolloffFactor = options.rolloffFactor || 1;
  57604. this.refDistance = options.refDistance || 1;
  57605. this.distanceModel = options.distanceModel || "linear";
  57606. this._playbackRate = options.playbackRate || 1;
  57607. this._streaming = options.streaming || false;
  57608. }
  57609. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57610. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  57611. this._soundGain.gain.value = this._volume;
  57612. this._inputAudioNode = this._soundGain;
  57613. this._ouputAudioNode = this._soundGain;
  57614. if (this.spatialSound) {
  57615. this._createSpatialParameters();
  57616. }
  57617. this._scene.mainSoundTrack.AddSound(this);
  57618. var validParameter = true;
  57619. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  57620. if (urlOrArrayBuffer) {
  57621. if (typeof (urlOrArrayBuffer) === "string")
  57622. this._urlType = "String";
  57623. if (Array.isArray(urlOrArrayBuffer))
  57624. this._urlType = "Array";
  57625. if (urlOrArrayBuffer instanceof ArrayBuffer)
  57626. this._urlType = "ArrayBuffer";
  57627. var urls = [];
  57628. var codecSupportedFound = false;
  57629. switch (this._urlType) {
  57630. case "ArrayBuffer":
  57631. if (urlOrArrayBuffer.byteLength > 0) {
  57632. codecSupportedFound = true;
  57633. this._soundLoaded(urlOrArrayBuffer);
  57634. }
  57635. break;
  57636. case "String":
  57637. urls.push(urlOrArrayBuffer);
  57638. case "Array":
  57639. if (urls.length === 0)
  57640. urls = urlOrArrayBuffer;
  57641. // If we found a supported format, we load it immediately and stop the loop
  57642. for (var i = 0; i < urls.length; i++) {
  57643. var url = urls[i];
  57644. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  57645. codecSupportedFound = true;
  57646. }
  57647. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  57648. codecSupportedFound = true;
  57649. }
  57650. if (url.indexOf(".wav", url.length - 4) !== -1) {
  57651. codecSupportedFound = true;
  57652. }
  57653. if (url.indexOf("blob:") !== -1) {
  57654. codecSupportedFound = true;
  57655. }
  57656. if (codecSupportedFound) {
  57657. // Loading sound using XHR2
  57658. if (!this._streaming) {
  57659. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  57660. }
  57661. else {
  57662. this._htmlAudioElement = new Audio(url);
  57663. this._htmlAudioElement.controls = false;
  57664. this._htmlAudioElement.loop = this.loop;
  57665. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  57666. this._htmlAudioElement.preload = "auto";
  57667. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  57668. _this._isReadyToPlay = true;
  57669. if (_this.autoplay) {
  57670. _this.play();
  57671. }
  57672. if (_this._readyToPlayCallback) {
  57673. _this._readyToPlayCallback();
  57674. }
  57675. });
  57676. document.body.appendChild(this._htmlAudioElement);
  57677. }
  57678. break;
  57679. }
  57680. }
  57681. break;
  57682. default:
  57683. validParameter = false;
  57684. break;
  57685. }
  57686. if (!validParameter) {
  57687. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  57688. }
  57689. else {
  57690. if (!codecSupportedFound) {
  57691. this._isReadyToPlay = true;
  57692. // Simulating a ready to play event to avoid breaking code path
  57693. if (this._readyToPlayCallback) {
  57694. window.setTimeout(function () {
  57695. if (_this._readyToPlayCallback) {
  57696. _this._readyToPlayCallback();
  57697. }
  57698. }, 1000);
  57699. }
  57700. }
  57701. }
  57702. }
  57703. }
  57704. else {
  57705. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  57706. this._scene.mainSoundTrack.AddSound(this);
  57707. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  57708. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  57709. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  57710. }
  57711. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  57712. if (this._readyToPlayCallback) {
  57713. window.setTimeout(function () {
  57714. if (_this._readyToPlayCallback) {
  57715. _this._readyToPlayCallback();
  57716. }
  57717. }, 1000);
  57718. }
  57719. }
  57720. }
  57721. Sound.prototype.dispose = function () {
  57722. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  57723. if (this.isPlaying) {
  57724. this.stop();
  57725. }
  57726. this._isReadyToPlay = false;
  57727. if (this.soundTrackId === -1) {
  57728. this._scene.mainSoundTrack.RemoveSound(this);
  57729. }
  57730. else {
  57731. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  57732. }
  57733. if (this._soundGain) {
  57734. this._soundGain.disconnect();
  57735. this._soundGain = null;
  57736. }
  57737. if (this._soundPanner) {
  57738. this._soundPanner.disconnect();
  57739. this._soundPanner = null;
  57740. }
  57741. if (this._soundSource) {
  57742. this._soundSource.disconnect();
  57743. this._soundSource = null;
  57744. }
  57745. this._audioBuffer = null;
  57746. if (this._htmlAudioElement) {
  57747. this._htmlAudioElement.pause();
  57748. this._htmlAudioElement.src = "";
  57749. document.body.removeChild(this._htmlAudioElement);
  57750. }
  57751. if (this._connectedMesh && this._registerFunc) {
  57752. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57753. this._connectedMesh = null;
  57754. }
  57755. }
  57756. };
  57757. Sound.prototype.isReady = function () {
  57758. return this._isReadyToPlay;
  57759. };
  57760. Sound.prototype._soundLoaded = function (audioData) {
  57761. var _this = this;
  57762. if (!BABYLON.Engine.audioEngine.audioContext) {
  57763. return;
  57764. }
  57765. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  57766. _this._audioBuffer = buffer;
  57767. _this._isReadyToPlay = true;
  57768. if (_this.autoplay) {
  57769. _this.play();
  57770. }
  57771. if (_this._readyToPlayCallback) {
  57772. _this._readyToPlayCallback();
  57773. }
  57774. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  57775. };
  57776. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  57777. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57778. this._audioBuffer = audioBuffer;
  57779. this._isReadyToPlay = true;
  57780. }
  57781. };
  57782. Sound.prototype.updateOptions = function (options) {
  57783. if (options) {
  57784. this.loop = options.loop || this.loop;
  57785. this.maxDistance = options.maxDistance || this.maxDistance;
  57786. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  57787. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  57788. this.refDistance = options.refDistance || this.refDistance;
  57789. this.distanceModel = options.distanceModel || this.distanceModel;
  57790. this._playbackRate = options.playbackRate || this._playbackRate;
  57791. this._updateSpatialParameters();
  57792. if (this.isPlaying) {
  57793. if (this._streaming) {
  57794. this._htmlAudioElement.playbackRate = this._playbackRate;
  57795. }
  57796. else {
  57797. if (this._soundSource) {
  57798. this._soundSource.playbackRate.value = this._playbackRate;
  57799. }
  57800. }
  57801. }
  57802. }
  57803. };
  57804. Sound.prototype._createSpatialParameters = function () {
  57805. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57806. if (this._scene.headphone) {
  57807. this._panningModel = "HRTF";
  57808. }
  57809. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  57810. this._updateSpatialParameters();
  57811. this._soundPanner.connect(this._ouputAudioNode);
  57812. this._inputAudioNode = this._soundPanner;
  57813. }
  57814. };
  57815. Sound.prototype._updateSpatialParameters = function () {
  57816. if (this.spatialSound && this._soundPanner) {
  57817. if (this.useCustomAttenuation) {
  57818. // Tricks to disable in a way embedded Web Audio attenuation
  57819. this._soundPanner.distanceModel = "linear";
  57820. this._soundPanner.maxDistance = Number.MAX_VALUE;
  57821. this._soundPanner.refDistance = 1;
  57822. this._soundPanner.rolloffFactor = 1;
  57823. this._soundPanner.panningModel = this._panningModel;
  57824. }
  57825. else {
  57826. this._soundPanner.distanceModel = this.distanceModel;
  57827. this._soundPanner.maxDistance = this.maxDistance;
  57828. this._soundPanner.refDistance = this.refDistance;
  57829. this._soundPanner.rolloffFactor = this.rolloffFactor;
  57830. this._soundPanner.panningModel = this._panningModel;
  57831. }
  57832. }
  57833. };
  57834. Sound.prototype.switchPanningModelToHRTF = function () {
  57835. this._panningModel = "HRTF";
  57836. this._switchPanningModel();
  57837. };
  57838. Sound.prototype.switchPanningModelToEqualPower = function () {
  57839. this._panningModel = "equalpower";
  57840. this._switchPanningModel();
  57841. };
  57842. Sound.prototype._switchPanningModel = function () {
  57843. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  57844. this._soundPanner.panningModel = this._panningModel;
  57845. }
  57846. };
  57847. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  57848. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57849. if (this._isOutputConnected) {
  57850. this._ouputAudioNode.disconnect();
  57851. }
  57852. this._ouputAudioNode.connect(soundTrackAudioNode);
  57853. this._isOutputConnected = true;
  57854. }
  57855. };
  57856. /**
  57857. * Transform this sound into a directional source
  57858. * @param coneInnerAngle Size of the inner cone in degree
  57859. * @param coneOuterAngle Size of the outer cone in degree
  57860. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  57861. */
  57862. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  57863. if (coneOuterAngle < coneInnerAngle) {
  57864. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  57865. return;
  57866. }
  57867. this._coneInnerAngle = coneInnerAngle;
  57868. this._coneOuterAngle = coneOuterAngle;
  57869. this._coneOuterGain = coneOuterGain;
  57870. this._isDirectional = true;
  57871. if (this.isPlaying && this.loop) {
  57872. this.stop();
  57873. this.play();
  57874. }
  57875. };
  57876. Sound.prototype.setPosition = function (newPosition) {
  57877. this._position = newPosition;
  57878. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  57879. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  57880. }
  57881. };
  57882. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  57883. this._localDirection = newLocalDirection;
  57884. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  57885. this._updateDirection();
  57886. }
  57887. };
  57888. Sound.prototype._updateDirection = function () {
  57889. if (!this._connectedMesh || !this._soundPanner) {
  57890. return;
  57891. }
  57892. var mat = this._connectedMesh.getWorldMatrix();
  57893. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  57894. direction.normalize();
  57895. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  57896. };
  57897. Sound.prototype.updateDistanceFromListener = function () {
  57898. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  57899. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  57900. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  57901. }
  57902. };
  57903. Sound.prototype.setAttenuationFunction = function (callback) {
  57904. this._customAttenuationFunction = callback;
  57905. };
  57906. /**
  57907. * Play the sound
  57908. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  57909. * @param offset (optional) Start the sound setting it at a specific time
  57910. */
  57911. Sound.prototype.play = function (time, offset) {
  57912. var _this = this;
  57913. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  57914. try {
  57915. if (this._startOffset < 0) {
  57916. time = -this._startOffset;
  57917. this._startOffset = 0;
  57918. }
  57919. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  57920. if (!this._soundSource || !this._streamingSource) {
  57921. if (this.spatialSound && this._soundPanner) {
  57922. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  57923. if (this._isDirectional) {
  57924. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  57925. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  57926. this._soundPanner.coneOuterGain = this._coneOuterGain;
  57927. if (this._connectedMesh) {
  57928. this._updateDirection();
  57929. }
  57930. else {
  57931. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  57932. }
  57933. }
  57934. }
  57935. }
  57936. if (this._streaming) {
  57937. if (!this._streamingSource) {
  57938. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  57939. this._htmlAudioElement.onended = function () { _this._onended(); };
  57940. this._htmlAudioElement.playbackRate = this._playbackRate;
  57941. }
  57942. this._streamingSource.disconnect();
  57943. this._streamingSource.connect(this._inputAudioNode);
  57944. this._htmlAudioElement.play();
  57945. }
  57946. else {
  57947. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  57948. this._soundSource.buffer = this._audioBuffer;
  57949. this._soundSource.connect(this._inputAudioNode);
  57950. this._soundSource.loop = this.loop;
  57951. this._soundSource.playbackRate.value = this._playbackRate;
  57952. this._soundSource.onended = function () { _this._onended(); };
  57953. if (this._soundSource.buffer) {
  57954. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  57955. }
  57956. }
  57957. this._startTime = startTime;
  57958. this.isPlaying = true;
  57959. this.isPaused = false;
  57960. }
  57961. catch (ex) {
  57962. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  57963. }
  57964. }
  57965. };
  57966. Sound.prototype._onended = function () {
  57967. this.isPlaying = false;
  57968. if (this.onended) {
  57969. this.onended();
  57970. }
  57971. };
  57972. /**
  57973. * Stop the sound
  57974. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  57975. */
  57976. Sound.prototype.stop = function (time) {
  57977. if (this.isPlaying) {
  57978. if (this._streaming) {
  57979. this._htmlAudioElement.pause();
  57980. // Test needed for Firefox or it will generate an Invalid State Error
  57981. if (this._htmlAudioElement.currentTime > 0) {
  57982. this._htmlAudioElement.currentTime = 0;
  57983. }
  57984. }
  57985. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  57986. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  57987. this._soundSource.stop(stopTime);
  57988. this._soundSource.onended = function () { };
  57989. if (!this.isPaused) {
  57990. this._startOffset = 0;
  57991. }
  57992. }
  57993. this.isPlaying = false;
  57994. }
  57995. };
  57996. Sound.prototype.pause = function () {
  57997. if (this.isPlaying) {
  57998. this.isPaused = true;
  57999. if (this._streaming) {
  58000. this._htmlAudioElement.pause();
  58001. }
  58002. else if (BABYLON.Engine.audioEngine.audioContext) {
  58003. this.stop(0);
  58004. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  58005. }
  58006. }
  58007. };
  58008. Sound.prototype.setVolume = function (newVolume, time) {
  58009. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  58010. if (time && BABYLON.Engine.audioEngine.audioContext) {
  58011. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  58012. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  58013. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  58014. }
  58015. else {
  58016. this._soundGain.gain.value = newVolume;
  58017. }
  58018. }
  58019. this._volume = newVolume;
  58020. };
  58021. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  58022. this._playbackRate = newPlaybackRate;
  58023. if (this.isPlaying) {
  58024. if (this._streaming) {
  58025. this._htmlAudioElement.playbackRate = this._playbackRate;
  58026. }
  58027. else if (this._soundSource) {
  58028. this._soundSource.playbackRate.value = this._playbackRate;
  58029. }
  58030. }
  58031. };
  58032. Sound.prototype.getVolume = function () {
  58033. return this._volume;
  58034. };
  58035. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  58036. var _this = this;
  58037. if (this._connectedMesh && this._registerFunc) {
  58038. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58039. this._registerFunc = null;
  58040. }
  58041. this._connectedMesh = meshToConnectTo;
  58042. if (!this.spatialSound) {
  58043. this.spatialSound = true;
  58044. this._createSpatialParameters();
  58045. if (this.isPlaying && this.loop) {
  58046. this.stop();
  58047. this.play();
  58048. }
  58049. }
  58050. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  58051. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  58052. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  58053. };
  58054. Sound.prototype.detachFromMesh = function () {
  58055. if (this._connectedMesh && this._registerFunc) {
  58056. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58057. this._registerFunc = null;
  58058. this._connectedMesh = null;
  58059. }
  58060. };
  58061. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  58062. if (!node.getBoundingInfo) {
  58063. return;
  58064. }
  58065. var mesh = node;
  58066. var boundingInfo = mesh.getBoundingInfo();
  58067. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  58068. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  58069. this._updateDirection();
  58070. }
  58071. };
  58072. Sound.prototype.clone = function () {
  58073. var _this = this;
  58074. if (!this._streaming) {
  58075. var setBufferAndRun = function () {
  58076. if (_this._isReadyToPlay) {
  58077. clonedSound._audioBuffer = _this.getAudioBuffer();
  58078. clonedSound._isReadyToPlay = true;
  58079. if (clonedSound.autoplay) {
  58080. clonedSound.play();
  58081. }
  58082. }
  58083. else {
  58084. window.setTimeout(setBufferAndRun, 300);
  58085. }
  58086. };
  58087. var currentOptions = {
  58088. autoplay: this.autoplay, loop: this.loop,
  58089. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  58090. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  58091. refDistance: this.refDistance, distanceModel: this.distanceModel
  58092. };
  58093. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  58094. if (this.useCustomAttenuation) {
  58095. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  58096. }
  58097. clonedSound.setPosition(this._position);
  58098. clonedSound.setPlaybackRate(this._playbackRate);
  58099. setBufferAndRun();
  58100. return clonedSound;
  58101. }
  58102. else {
  58103. return null;
  58104. }
  58105. };
  58106. Sound.prototype.getAudioBuffer = function () {
  58107. return this._audioBuffer;
  58108. };
  58109. Sound.prototype.serialize = function () {
  58110. var serializationObject = {
  58111. name: this.name,
  58112. url: this.name,
  58113. autoplay: this.autoplay,
  58114. loop: this.loop,
  58115. volume: this._volume,
  58116. spatialSound: this.spatialSound,
  58117. maxDistance: this.maxDistance,
  58118. rolloffFactor: this.rolloffFactor,
  58119. refDistance: this.refDistance,
  58120. distanceModel: this.distanceModel,
  58121. playbackRate: this._playbackRate,
  58122. panningModel: this._panningModel,
  58123. soundTrackId: this.soundTrackId
  58124. };
  58125. if (this.spatialSound) {
  58126. if (this._connectedMesh)
  58127. serializationObject.connectedMeshId = this._connectedMesh.id;
  58128. serializationObject.position = this._position.asArray();
  58129. serializationObject.refDistance = this.refDistance;
  58130. serializationObject.distanceModel = this.distanceModel;
  58131. serializationObject.isDirectional = this._isDirectional;
  58132. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  58133. serializationObject.coneInnerAngle = this._coneInnerAngle;
  58134. serializationObject.coneOuterAngle = this._coneOuterAngle;
  58135. serializationObject.coneOuterGain = this._coneOuterGain;
  58136. }
  58137. return serializationObject;
  58138. };
  58139. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  58140. var soundName = parsedSound.name;
  58141. var soundUrl;
  58142. if (parsedSound.url) {
  58143. soundUrl = rootUrl + parsedSound.url;
  58144. }
  58145. else {
  58146. soundUrl = rootUrl + soundName;
  58147. }
  58148. var options = {
  58149. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  58150. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  58151. rolloffFactor: parsedSound.rolloffFactor,
  58152. refDistance: parsedSound.refDistance,
  58153. distanceModel: parsedSound.distanceModel,
  58154. playbackRate: parsedSound.playbackRate
  58155. };
  58156. var newSound;
  58157. if (!sourceSound) {
  58158. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  58159. scene._addPendingData(newSound);
  58160. }
  58161. else {
  58162. var setBufferAndRun = function () {
  58163. if (sourceSound._isReadyToPlay) {
  58164. newSound._audioBuffer = sourceSound.getAudioBuffer();
  58165. newSound._isReadyToPlay = true;
  58166. if (newSound.autoplay) {
  58167. newSound.play();
  58168. }
  58169. }
  58170. else {
  58171. window.setTimeout(setBufferAndRun, 300);
  58172. }
  58173. };
  58174. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  58175. setBufferAndRun();
  58176. }
  58177. if (parsedSound.position) {
  58178. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  58179. newSound.setPosition(soundPosition);
  58180. }
  58181. if (parsedSound.isDirectional) {
  58182. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  58183. if (parsedSound.localDirectionToMesh) {
  58184. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  58185. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  58186. }
  58187. }
  58188. if (parsedSound.connectedMeshId) {
  58189. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  58190. if (connectedMesh) {
  58191. newSound.attachToMesh(connectedMesh);
  58192. }
  58193. }
  58194. return newSound;
  58195. };
  58196. return Sound;
  58197. }());
  58198. BABYLON.Sound = Sound;
  58199. })(BABYLON || (BABYLON = {}));
  58200. //# sourceMappingURL=babylon.sound.js.map
  58201. var BABYLON;
  58202. (function (BABYLON) {
  58203. var SoundTrack = /** @class */ (function () {
  58204. function SoundTrack(scene, options) {
  58205. this.id = -1;
  58206. this._isMainTrack = false;
  58207. this._isInitialized = false;
  58208. this._scene = scene;
  58209. this.soundCollection = new Array();
  58210. this._options = options;
  58211. if (!this._isMainTrack) {
  58212. this._scene.soundTracks.push(this);
  58213. this.id = this._scene.soundTracks.length - 1;
  58214. }
  58215. }
  58216. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  58217. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  58218. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  58219. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  58220. if (this._options) {
  58221. if (this._options.volume) {
  58222. this._outputAudioNode.gain.value = this._options.volume;
  58223. }
  58224. if (this._options.mainTrack) {
  58225. this._isMainTrack = this._options.mainTrack;
  58226. }
  58227. }
  58228. this._isInitialized = true;
  58229. }
  58230. };
  58231. SoundTrack.prototype.dispose = function () {
  58232. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  58233. if (this._connectedAnalyser) {
  58234. this._connectedAnalyser.stopDebugCanvas();
  58235. }
  58236. while (this.soundCollection.length) {
  58237. this.soundCollection[0].dispose();
  58238. }
  58239. if (this._outputAudioNode) {
  58240. this._outputAudioNode.disconnect();
  58241. }
  58242. this._outputAudioNode = null;
  58243. }
  58244. };
  58245. SoundTrack.prototype.AddSound = function (sound) {
  58246. if (!this._isInitialized) {
  58247. this._initializeSoundTrackAudioGraph();
  58248. }
  58249. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58250. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  58251. }
  58252. if (sound.soundTrackId) {
  58253. if (sound.soundTrackId === -1) {
  58254. this._scene.mainSoundTrack.RemoveSound(sound);
  58255. }
  58256. else {
  58257. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  58258. }
  58259. }
  58260. this.soundCollection.push(sound);
  58261. sound.soundTrackId = this.id;
  58262. };
  58263. SoundTrack.prototype.RemoveSound = function (sound) {
  58264. var index = this.soundCollection.indexOf(sound);
  58265. if (index !== -1) {
  58266. this.soundCollection.splice(index, 1);
  58267. }
  58268. };
  58269. SoundTrack.prototype.setVolume = function (newVolume) {
  58270. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58271. this._outputAudioNode.gain.value = newVolume;
  58272. }
  58273. };
  58274. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  58275. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58276. for (var i = 0; i < this.soundCollection.length; i++) {
  58277. this.soundCollection[i].switchPanningModelToHRTF();
  58278. }
  58279. }
  58280. };
  58281. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  58282. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58283. for (var i = 0; i < this.soundCollection.length; i++) {
  58284. this.soundCollection[i].switchPanningModelToEqualPower();
  58285. }
  58286. }
  58287. };
  58288. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  58289. if (this._connectedAnalyser) {
  58290. this._connectedAnalyser.stopDebugCanvas();
  58291. }
  58292. this._connectedAnalyser = analyser;
  58293. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58294. this._outputAudioNode.disconnect();
  58295. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  58296. }
  58297. };
  58298. return SoundTrack;
  58299. }());
  58300. BABYLON.SoundTrack = SoundTrack;
  58301. })(BABYLON || (BABYLON = {}));
  58302. //# sourceMappingURL=babylon.soundtrack.js.map
  58303. var BABYLON;
  58304. (function (BABYLON) {
  58305. var Analyser = /** @class */ (function () {
  58306. function Analyser(scene) {
  58307. this.SMOOTHING = 0.75;
  58308. this.FFT_SIZE = 512;
  58309. this.BARGRAPHAMPLITUDE = 256;
  58310. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  58311. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  58312. this._scene = scene;
  58313. this._audioEngine = BABYLON.Engine.audioEngine;
  58314. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  58315. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  58316. this._webAudioAnalyser.minDecibels = -140;
  58317. this._webAudioAnalyser.maxDecibels = 0;
  58318. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  58319. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  58320. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  58321. }
  58322. }
  58323. Analyser.prototype.getFrequencyBinCount = function () {
  58324. if (this._audioEngine.canUseWebAudio) {
  58325. return this._webAudioAnalyser.frequencyBinCount;
  58326. }
  58327. else {
  58328. return 0;
  58329. }
  58330. };
  58331. Analyser.prototype.getByteFrequencyData = function () {
  58332. if (this._audioEngine.canUseWebAudio) {
  58333. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58334. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58335. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  58336. }
  58337. return this._byteFreqs;
  58338. };
  58339. Analyser.prototype.getByteTimeDomainData = function () {
  58340. if (this._audioEngine.canUseWebAudio) {
  58341. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58342. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58343. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  58344. }
  58345. return this._byteTime;
  58346. };
  58347. Analyser.prototype.getFloatFrequencyData = function () {
  58348. if (this._audioEngine.canUseWebAudio) {
  58349. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58350. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58351. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  58352. }
  58353. return this._floatFreqs;
  58354. };
  58355. Analyser.prototype.drawDebugCanvas = function () {
  58356. var _this = this;
  58357. if (this._audioEngine.canUseWebAudio) {
  58358. if (!this._debugCanvas) {
  58359. this._debugCanvas = document.createElement("canvas");
  58360. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  58361. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  58362. this._debugCanvas.style.position = "absolute";
  58363. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  58364. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  58365. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  58366. document.body.appendChild(this._debugCanvas);
  58367. this._registerFunc = function () {
  58368. _this.drawDebugCanvas();
  58369. };
  58370. this._scene.registerBeforeRender(this._registerFunc);
  58371. }
  58372. if (this._registerFunc && this._debugCanvasContext) {
  58373. var workingArray = this.getByteFrequencyData();
  58374. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  58375. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  58376. // Draw the frequency domain chart.
  58377. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  58378. var value = workingArray[i];
  58379. var percent = value / this.BARGRAPHAMPLITUDE;
  58380. var height = this.DEBUGCANVASSIZE.height * percent;
  58381. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  58382. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  58383. var hue = i / this.getFrequencyBinCount() * 360;
  58384. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  58385. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  58386. }
  58387. }
  58388. }
  58389. };
  58390. Analyser.prototype.stopDebugCanvas = function () {
  58391. if (this._debugCanvas) {
  58392. if (this._registerFunc) {
  58393. this._scene.unregisterBeforeRender(this._registerFunc);
  58394. this._registerFunc = null;
  58395. }
  58396. document.body.removeChild(this._debugCanvas);
  58397. this._debugCanvas = null;
  58398. this._debugCanvasContext = null;
  58399. }
  58400. };
  58401. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  58402. if (this._audioEngine.canUseWebAudio) {
  58403. inputAudioNode.connect(this._webAudioAnalyser);
  58404. this._webAudioAnalyser.connect(outputAudioNode);
  58405. }
  58406. };
  58407. Analyser.prototype.dispose = function () {
  58408. if (this._audioEngine.canUseWebAudio) {
  58409. this._webAudioAnalyser.disconnect();
  58410. }
  58411. };
  58412. return Analyser;
  58413. }());
  58414. BABYLON.Analyser = Analyser;
  58415. })(BABYLON || (BABYLON = {}));
  58416. //# sourceMappingURL=babylon.analyser.js.map
  58417. var BABYLON;
  58418. (function (BABYLON) {
  58419. var CubeTexture = /** @class */ (function (_super) {
  58420. __extends(CubeTexture, _super);
  58421. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  58422. if (extensions === void 0) { extensions = null; }
  58423. if (noMipmap === void 0) { noMipmap = false; }
  58424. if (files === void 0) { files = null; }
  58425. if (onLoad === void 0) { onLoad = null; }
  58426. if (onError === void 0) { onError = null; }
  58427. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  58428. if (prefiltered === void 0) { prefiltered = false; }
  58429. if (forcedExtension === void 0) { forcedExtension = null; }
  58430. var _this = _super.call(this, scene) || this;
  58431. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  58432. /**
  58433. * Gets or sets the center of the bounding box associated with the cube texture
  58434. * It must define where the camera used to render the texture was set
  58435. */
  58436. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  58437. _this.name = rootUrl;
  58438. _this.url = rootUrl;
  58439. _this._noMipmap = noMipmap;
  58440. _this.hasAlpha = false;
  58441. _this._format = format;
  58442. _this._prefiltered = prefiltered;
  58443. _this.isCube = true;
  58444. _this._textureMatrix = BABYLON.Matrix.Identity();
  58445. if (prefiltered) {
  58446. _this.gammaSpace = false;
  58447. }
  58448. if (!rootUrl && !files) {
  58449. return _this;
  58450. }
  58451. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  58452. var lastDot = rootUrl.lastIndexOf(".");
  58453. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  58454. var isDDS = (extension === ".dds");
  58455. if (!files) {
  58456. if (!isDDS && !extensions) {
  58457. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  58458. }
  58459. files = [];
  58460. if (extensions) {
  58461. for (var index = 0; index < extensions.length; index++) {
  58462. files.push(rootUrl + extensions[index]);
  58463. }
  58464. }
  58465. }
  58466. _this._files = files;
  58467. if (!_this._texture) {
  58468. if (!scene.useDelayedTextureLoading) {
  58469. if (prefiltered) {
  58470. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  58471. }
  58472. else {
  58473. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  58474. }
  58475. }
  58476. else {
  58477. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  58478. }
  58479. }
  58480. else if (onLoad) {
  58481. if (_this._texture.isReady) {
  58482. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  58483. }
  58484. else {
  58485. _this._texture.onLoadedObservable.add(onLoad);
  58486. }
  58487. }
  58488. return _this;
  58489. }
  58490. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  58491. get: function () {
  58492. return this._boundingBoxSize;
  58493. },
  58494. /**
  58495. * Gets or sets the size of the bounding box associated with the cube texture
  58496. * When defined, the cubemap will switch to local mode
  58497. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  58498. * @example https://www.babylonjs-playground.com/#RNASML
  58499. */
  58500. set: function (value) {
  58501. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  58502. return;
  58503. }
  58504. this._boundingBoxSize = value;
  58505. var scene = this.getScene();
  58506. if (scene) {
  58507. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  58508. }
  58509. },
  58510. enumerable: true,
  58511. configurable: true
  58512. });
  58513. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  58514. var rootUrlKey = "";
  58515. files.forEach(function (url) { return rootUrlKey += url; });
  58516. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  58517. };
  58518. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  58519. if (forcedExtension === void 0) { forcedExtension = null; }
  58520. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  58521. };
  58522. // Methods
  58523. CubeTexture.prototype.delayLoad = function () {
  58524. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  58525. return;
  58526. }
  58527. var scene = this.getScene();
  58528. if (!scene) {
  58529. return;
  58530. }
  58531. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  58532. this._texture = this._getFromCache(this.url, this._noMipmap);
  58533. if (!this._texture) {
  58534. if (this._prefiltered) {
  58535. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  58536. }
  58537. else {
  58538. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  58539. }
  58540. }
  58541. };
  58542. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  58543. return this._textureMatrix;
  58544. };
  58545. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  58546. this._textureMatrix = value;
  58547. };
  58548. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  58549. var texture = BABYLON.SerializationHelper.Parse(function () {
  58550. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  58551. }, parsedTexture, scene);
  58552. // Local Cubemaps
  58553. if (parsedTexture.boundingBoxPosition) {
  58554. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  58555. }
  58556. if (parsedTexture.boundingBoxSize) {
  58557. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  58558. }
  58559. // Animations
  58560. if (parsedTexture.animations) {
  58561. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  58562. var parsedAnimation = parsedTexture.animations[animationIndex];
  58563. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  58564. }
  58565. }
  58566. return texture;
  58567. };
  58568. CubeTexture.prototype.clone = function () {
  58569. var _this = this;
  58570. return BABYLON.SerializationHelper.Clone(function () {
  58571. var scene = _this.getScene();
  58572. if (!scene) {
  58573. return _this;
  58574. }
  58575. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  58576. }, this);
  58577. };
  58578. return CubeTexture;
  58579. }(BABYLON.BaseTexture));
  58580. BABYLON.CubeTexture = CubeTexture;
  58581. })(BABYLON || (BABYLON = {}));
  58582. //# sourceMappingURL=babylon.cubeTexture.js.map
  58583. var BABYLON;
  58584. (function (BABYLON) {
  58585. var RenderTargetTexture = /** @class */ (function (_super) {
  58586. __extends(RenderTargetTexture, _super);
  58587. /**
  58588. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  58589. * or used a shadow, depth texture...
  58590. * @param name The friendly name of the texture
  58591. * @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)
  58592. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  58593. * @param generateMipMaps True if mip maps need to be generated after render.
  58594. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  58595. * @param type The type of the buffer in the RTT (int, half float, float...)
  58596. * @param isCube True if a cube texture needs to be created
  58597. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  58598. * @param generateDepthBuffer True to generate a depth buffer
  58599. * @param generateStencilBuffer True to generate a stencil buffer
  58600. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  58601. */
  58602. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  58603. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  58604. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58605. if (isCube === void 0) { isCube = false; }
  58606. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58607. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  58608. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  58609. if (isMulti === void 0) { isMulti = false; }
  58610. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  58611. _this.isCube = isCube;
  58612. /**
  58613. * Use this list to define the list of mesh you want to render.
  58614. */
  58615. _this.renderList = new Array();
  58616. _this.renderParticles = true;
  58617. _this.renderSprites = false;
  58618. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  58619. _this.ignoreCameraViewport = false;
  58620. // Events
  58621. /**
  58622. * An event triggered when the texture is unbind.
  58623. * @type {BABYLON.Observable}
  58624. */
  58625. _this.onBeforeBindObservable = new BABYLON.Observable();
  58626. /**
  58627. * An event triggered when the texture is unbind.
  58628. * @type {BABYLON.Observable}
  58629. */
  58630. _this.onAfterUnbindObservable = new BABYLON.Observable();
  58631. /**
  58632. * An event triggered before rendering the texture
  58633. * @type {BABYLON.Observable}
  58634. */
  58635. _this.onBeforeRenderObservable = new BABYLON.Observable();
  58636. /**
  58637. * An event triggered after rendering the texture
  58638. * @type {BABYLON.Observable}
  58639. */
  58640. _this.onAfterRenderObservable = new BABYLON.Observable();
  58641. /**
  58642. * An event triggered after the texture clear
  58643. * @type {BABYLON.Observable}
  58644. */
  58645. _this.onClearObservable = new BABYLON.Observable();
  58646. _this._currentRefreshId = -1;
  58647. _this._refreshRate = 1;
  58648. _this._samples = 1;
  58649. /**
  58650. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  58651. * It must define where the camera used to render the texture is set
  58652. */
  58653. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  58654. scene = _this.getScene();
  58655. if (!scene) {
  58656. return _this;
  58657. }
  58658. _this._engine = scene.getEngine();
  58659. _this.name = name;
  58660. _this.isRenderTarget = true;
  58661. _this._initialSizeParameter = size;
  58662. _this._processSizeParameter(size);
  58663. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  58664. });
  58665. _this._generateMipMaps = generateMipMaps ? true : false;
  58666. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  58667. // Rendering groups
  58668. _this._renderingManager = new BABYLON.RenderingManager(scene);
  58669. if (isMulti) {
  58670. return _this;
  58671. }
  58672. _this._renderTargetOptions = {
  58673. generateMipMaps: generateMipMaps,
  58674. type: type,
  58675. samplingMode: samplingMode,
  58676. generateDepthBuffer: generateDepthBuffer,
  58677. generateStencilBuffer: generateStencilBuffer
  58678. };
  58679. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  58680. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58681. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58682. }
  58683. if (isCube) {
  58684. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  58685. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  58686. _this._textureMatrix = BABYLON.Matrix.Identity();
  58687. }
  58688. else {
  58689. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  58690. }
  58691. return _this;
  58692. }
  58693. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  58694. get: function () {
  58695. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  58696. },
  58697. enumerable: true,
  58698. configurable: true
  58699. });
  58700. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  58701. get: function () {
  58702. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  58703. },
  58704. enumerable: true,
  58705. configurable: true
  58706. });
  58707. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  58708. get: function () {
  58709. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  58710. },
  58711. enumerable: true,
  58712. configurable: true
  58713. });
  58714. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  58715. set: function (callback) {
  58716. if (this._onAfterUnbindObserver) {
  58717. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  58718. }
  58719. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  58720. },
  58721. enumerable: true,
  58722. configurable: true
  58723. });
  58724. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  58725. set: function (callback) {
  58726. if (this._onBeforeRenderObserver) {
  58727. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  58728. }
  58729. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  58730. },
  58731. enumerable: true,
  58732. configurable: true
  58733. });
  58734. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  58735. set: function (callback) {
  58736. if (this._onAfterRenderObserver) {
  58737. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  58738. }
  58739. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  58740. },
  58741. enumerable: true,
  58742. configurable: true
  58743. });
  58744. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  58745. set: function (callback) {
  58746. if (this._onClearObserver) {
  58747. this.onClearObservable.remove(this._onClearObserver);
  58748. }
  58749. this._onClearObserver = this.onClearObservable.add(callback);
  58750. },
  58751. enumerable: true,
  58752. configurable: true
  58753. });
  58754. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  58755. get: function () {
  58756. return this._renderTargetOptions;
  58757. },
  58758. enumerable: true,
  58759. configurable: true
  58760. });
  58761. RenderTargetTexture.prototype._onRatioRescale = function () {
  58762. if (this._sizeRatio) {
  58763. this.resize(this._initialSizeParameter);
  58764. }
  58765. };
  58766. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  58767. get: function () {
  58768. return this._boundingBoxSize;
  58769. },
  58770. /**
  58771. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  58772. * When defined, the cubemap will switch to local mode
  58773. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  58774. * @example https://www.babylonjs-playground.com/#RNASML
  58775. */
  58776. set: function (value) {
  58777. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  58778. return;
  58779. }
  58780. this._boundingBoxSize = value;
  58781. var scene = this.getScene();
  58782. if (scene) {
  58783. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  58784. }
  58785. },
  58786. enumerable: true,
  58787. configurable: true
  58788. });
  58789. /**
  58790. * Creates a depth stencil texture.
  58791. * This is only available in WebGL 2 or with the depth texture extension available.
  58792. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  58793. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  58794. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  58795. */
  58796. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  58797. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  58798. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  58799. if (generateStencil === void 0) { generateStencil = false; }
  58800. if (!this.getScene()) {
  58801. return;
  58802. }
  58803. var engine = this.getScene().getEngine();
  58804. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  58805. bilinearFiltering: bilinearFiltering,
  58806. comparisonFunction: comparisonFunction,
  58807. generateStencil: generateStencil,
  58808. isCube: this.isCube
  58809. });
  58810. engine.setFrameBufferDepthStencilTexture(this);
  58811. };
  58812. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  58813. if (size.ratio) {
  58814. this._sizeRatio = size.ratio;
  58815. this._size = {
  58816. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  58817. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  58818. };
  58819. }
  58820. else {
  58821. this._size = size;
  58822. }
  58823. };
  58824. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  58825. get: function () {
  58826. return this._samples;
  58827. },
  58828. set: function (value) {
  58829. if (this._samples === value) {
  58830. return;
  58831. }
  58832. var scene = this.getScene();
  58833. if (!scene) {
  58834. return;
  58835. }
  58836. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  58837. },
  58838. enumerable: true,
  58839. configurable: true
  58840. });
  58841. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  58842. this._currentRefreshId = -1;
  58843. };
  58844. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  58845. get: function () {
  58846. return this._refreshRate;
  58847. },
  58848. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  58849. set: function (value) {
  58850. this._refreshRate = value;
  58851. this.resetRefreshCounter();
  58852. },
  58853. enumerable: true,
  58854. configurable: true
  58855. });
  58856. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  58857. if (!this._postProcessManager) {
  58858. var scene = this.getScene();
  58859. if (!scene) {
  58860. return;
  58861. }
  58862. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  58863. this._postProcesses = new Array();
  58864. }
  58865. this._postProcesses.push(postProcess);
  58866. this._postProcesses[0].autoClear = false;
  58867. };
  58868. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  58869. if (!this._postProcesses) {
  58870. return;
  58871. }
  58872. if (dispose) {
  58873. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  58874. var postProcess = _a[_i];
  58875. postProcess.dispose();
  58876. }
  58877. }
  58878. this._postProcesses = [];
  58879. };
  58880. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  58881. if (!this._postProcesses) {
  58882. return;
  58883. }
  58884. var index = this._postProcesses.indexOf(postProcess);
  58885. if (index === -1) {
  58886. return;
  58887. }
  58888. this._postProcesses.splice(index, 1);
  58889. if (this._postProcesses.length > 0) {
  58890. this._postProcesses[0].autoClear = false;
  58891. }
  58892. };
  58893. RenderTargetTexture.prototype._shouldRender = function () {
  58894. if (this._currentRefreshId === -1) {
  58895. this._currentRefreshId = 1;
  58896. return true;
  58897. }
  58898. if (this.refreshRate === this._currentRefreshId) {
  58899. this._currentRefreshId = 1;
  58900. return true;
  58901. }
  58902. this._currentRefreshId++;
  58903. return false;
  58904. };
  58905. RenderTargetTexture.prototype.getRenderSize = function () {
  58906. if (this._size.width) {
  58907. return this._size.width;
  58908. }
  58909. return this._size;
  58910. };
  58911. RenderTargetTexture.prototype.getRenderWidth = function () {
  58912. if (this._size.width) {
  58913. return this._size.width;
  58914. }
  58915. return this._size;
  58916. };
  58917. RenderTargetTexture.prototype.getRenderHeight = function () {
  58918. if (this._size.width) {
  58919. return this._size.height;
  58920. }
  58921. return this._size;
  58922. };
  58923. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  58924. get: function () {
  58925. return true;
  58926. },
  58927. enumerable: true,
  58928. configurable: true
  58929. });
  58930. RenderTargetTexture.prototype.scale = function (ratio) {
  58931. var newSize = this.getRenderSize() * ratio;
  58932. this.resize(newSize);
  58933. };
  58934. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  58935. if (this.isCube) {
  58936. return this._textureMatrix;
  58937. }
  58938. return _super.prototype.getReflectionTextureMatrix.call(this);
  58939. };
  58940. RenderTargetTexture.prototype.resize = function (size) {
  58941. this.releaseInternalTexture();
  58942. var scene = this.getScene();
  58943. if (!scene) {
  58944. return;
  58945. }
  58946. this._processSizeParameter(size);
  58947. if (this.isCube) {
  58948. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  58949. }
  58950. else {
  58951. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  58952. }
  58953. };
  58954. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  58955. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  58956. if (dumpForDebug === void 0) { dumpForDebug = false; }
  58957. var scene = this.getScene();
  58958. if (!scene) {
  58959. return;
  58960. }
  58961. var engine = scene.getEngine();
  58962. if (this.useCameraPostProcesses !== undefined) {
  58963. useCameraPostProcess = this.useCameraPostProcesses;
  58964. }
  58965. if (this._waitingRenderList) {
  58966. this.renderList = [];
  58967. for (var index = 0; index < this._waitingRenderList.length; index++) {
  58968. var id = this._waitingRenderList[index];
  58969. var mesh_1 = scene.getMeshByID(id);
  58970. if (mesh_1) {
  58971. this.renderList.push(mesh_1);
  58972. }
  58973. }
  58974. delete this._waitingRenderList;
  58975. }
  58976. // Is predicate defined?
  58977. if (this.renderListPredicate) {
  58978. if (this.renderList) {
  58979. this.renderList.splice(0); // Clear previous renderList
  58980. }
  58981. else {
  58982. this.renderList = [];
  58983. }
  58984. var scene = this.getScene();
  58985. if (!scene) {
  58986. return;
  58987. }
  58988. var sceneMeshes = scene.meshes;
  58989. for (var index = 0; index < sceneMeshes.length; index++) {
  58990. var mesh = sceneMeshes[index];
  58991. if (this.renderListPredicate(mesh)) {
  58992. this.renderList.push(mesh);
  58993. }
  58994. }
  58995. }
  58996. this.onBeforeBindObservable.notifyObservers(this);
  58997. // Set custom projection.
  58998. // Needs to be before binding to prevent changing the aspect ratio.
  58999. var camera;
  59000. if (this.activeCamera) {
  59001. camera = this.activeCamera;
  59002. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  59003. if (this.activeCamera !== scene.activeCamera) {
  59004. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  59005. }
  59006. }
  59007. else {
  59008. camera = scene.activeCamera;
  59009. if (camera) {
  59010. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  59011. }
  59012. }
  59013. // Prepare renderingManager
  59014. this._renderingManager.reset();
  59015. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  59016. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  59017. var sceneRenderId = scene.getRenderId();
  59018. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  59019. var mesh = currentRenderList[meshIndex];
  59020. if (mesh) {
  59021. if (!mesh.isReady(this.refreshRate === 0)) {
  59022. this.resetRefreshCounter();
  59023. continue;
  59024. }
  59025. mesh._preActivateForIntermediateRendering(sceneRenderId);
  59026. var isMasked = void 0;
  59027. if (!this.renderList && camera) {
  59028. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  59029. }
  59030. else {
  59031. isMasked = false;
  59032. }
  59033. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  59034. mesh._activate(sceneRenderId);
  59035. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  59036. var subMesh = mesh.subMeshes[subIndex];
  59037. scene._activeIndices.addCount(subMesh.indexCount, false);
  59038. this._renderingManager.dispatch(subMesh, mesh);
  59039. }
  59040. }
  59041. }
  59042. }
  59043. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  59044. var particleSystem = scene.particleSystems[particleIndex];
  59045. var emitter = particleSystem.emitter;
  59046. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  59047. continue;
  59048. }
  59049. if (currentRenderList.indexOf(emitter) >= 0) {
  59050. this._renderingManager.dispatchParticles(particleSystem);
  59051. }
  59052. }
  59053. if (this.isCube) {
  59054. for (var face = 0; face < 6; face++) {
  59055. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  59056. scene.incrementRenderId();
  59057. scene.resetCachedMaterial();
  59058. }
  59059. }
  59060. else {
  59061. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  59062. }
  59063. this.onAfterUnbindObservable.notifyObservers(this);
  59064. if (scene.activeCamera) {
  59065. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  59066. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  59067. }
  59068. engine.setViewport(scene.activeCamera.viewport);
  59069. }
  59070. scene.resetCachedMaterial();
  59071. };
  59072. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  59073. var minimum = 128;
  59074. var x = renderDimension * scale;
  59075. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  59076. // Ensure we don't exceed the render dimension (while staying POT)
  59077. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  59078. };
  59079. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  59080. var _this = this;
  59081. if (!this._texture) {
  59082. return;
  59083. }
  59084. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  59085. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  59086. });
  59087. };
  59088. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  59089. var scene = this.getScene();
  59090. if (!scene) {
  59091. return;
  59092. }
  59093. var engine = scene.getEngine();
  59094. if (!this._texture) {
  59095. return;
  59096. }
  59097. // Bind
  59098. if (this._postProcessManager) {
  59099. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  59100. }
  59101. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  59102. if (this._texture) {
  59103. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  59104. }
  59105. }
  59106. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  59107. // Clear
  59108. if (this.onClearObservable.hasObservers()) {
  59109. this.onClearObservable.notifyObservers(engine);
  59110. }
  59111. else {
  59112. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  59113. }
  59114. if (!this._doNotChangeAspectRatio) {
  59115. scene.updateTransformMatrix(true);
  59116. }
  59117. // Render
  59118. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  59119. if (this._postProcessManager) {
  59120. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  59121. }
  59122. else if (useCameraPostProcess) {
  59123. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  59124. }
  59125. if (!this._doNotChangeAspectRatio) {
  59126. scene.updateTransformMatrix(true);
  59127. }
  59128. // Dump ?
  59129. if (dumpForDebug) {
  59130. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  59131. }
  59132. // Unbind
  59133. if (!this.isCube || faceIndex === 5) {
  59134. if (this.isCube) {
  59135. if (faceIndex === 5) {
  59136. engine.generateMipMapsForCubemap(this._texture);
  59137. }
  59138. }
  59139. this.unbindFrameBuffer(engine, faceIndex);
  59140. }
  59141. else {
  59142. this.onAfterRenderObservable.notifyObservers(faceIndex);
  59143. }
  59144. };
  59145. /**
  59146. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  59147. * This allowed control for front to back rendering or reversly depending of the special needs.
  59148. *
  59149. * @param renderingGroupId The rendering group id corresponding to its index
  59150. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  59151. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  59152. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  59153. */
  59154. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  59155. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  59156. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  59157. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  59158. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  59159. };
  59160. /**
  59161. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  59162. *
  59163. * @param renderingGroupId The rendering group id corresponding to its index
  59164. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  59165. */
  59166. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  59167. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  59168. };
  59169. RenderTargetTexture.prototype.clone = function () {
  59170. var textureSize = this.getSize();
  59171. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  59172. // Base texture
  59173. newTexture.hasAlpha = this.hasAlpha;
  59174. newTexture.level = this.level;
  59175. // RenderTarget Texture
  59176. newTexture.coordinatesMode = this.coordinatesMode;
  59177. if (this.renderList) {
  59178. newTexture.renderList = this.renderList.slice(0);
  59179. }
  59180. return newTexture;
  59181. };
  59182. RenderTargetTexture.prototype.serialize = function () {
  59183. if (!this.name) {
  59184. return null;
  59185. }
  59186. var serializationObject = _super.prototype.serialize.call(this);
  59187. serializationObject.renderTargetSize = this.getRenderSize();
  59188. serializationObject.renderList = [];
  59189. if (this.renderList) {
  59190. for (var index = 0; index < this.renderList.length; index++) {
  59191. serializationObject.renderList.push(this.renderList[index].id);
  59192. }
  59193. }
  59194. return serializationObject;
  59195. };
  59196. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  59197. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  59198. var objBuffer = this.getInternalTexture();
  59199. var scene = this.getScene();
  59200. if (objBuffer && scene) {
  59201. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  59202. }
  59203. };
  59204. RenderTargetTexture.prototype.dispose = function () {
  59205. if (this._postProcessManager) {
  59206. this._postProcessManager.dispose();
  59207. this._postProcessManager = null;
  59208. }
  59209. this.clearPostProcesses(true);
  59210. if (this._resizeObserver) {
  59211. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  59212. this._resizeObserver = null;
  59213. }
  59214. this.renderList = null;
  59215. // Remove from custom render targets
  59216. var scene = this.getScene();
  59217. if (!scene) {
  59218. return;
  59219. }
  59220. var index = scene.customRenderTargets.indexOf(this);
  59221. if (index >= 0) {
  59222. scene.customRenderTargets.splice(index, 1);
  59223. }
  59224. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  59225. var camera = _a[_i];
  59226. index = camera.customRenderTargets.indexOf(this);
  59227. if (index >= 0) {
  59228. camera.customRenderTargets.splice(index, 1);
  59229. }
  59230. }
  59231. _super.prototype.dispose.call(this);
  59232. };
  59233. RenderTargetTexture.prototype._rebuild = function () {
  59234. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  59235. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  59236. }
  59237. if (this._postProcessManager) {
  59238. this._postProcessManager._rebuild();
  59239. }
  59240. };
  59241. /**
  59242. * Clear the info related to rendering groups preventing retention point in material dispose.
  59243. */
  59244. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  59245. if (this._renderingManager) {
  59246. this._renderingManager.freeRenderingGroups();
  59247. }
  59248. };
  59249. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  59250. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  59251. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  59252. return RenderTargetTexture;
  59253. }(BABYLON.Texture));
  59254. BABYLON.RenderTargetTexture = RenderTargetTexture;
  59255. })(BABYLON || (BABYLON = {}));
  59256. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  59257. var BABYLON;
  59258. (function (BABYLON) {
  59259. ;
  59260. var MultiRenderTarget = /** @class */ (function (_super) {
  59261. __extends(MultiRenderTarget, _super);
  59262. function MultiRenderTarget(name, size, count, scene, options) {
  59263. var _this = this;
  59264. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  59265. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  59266. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  59267. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  59268. _this._engine = scene.getEngine();
  59269. if (!_this.isSupported) {
  59270. _this.dispose();
  59271. return;
  59272. }
  59273. var types = [];
  59274. var samplingModes = [];
  59275. for (var i = 0; i < count; i++) {
  59276. if (options && options.types && options.types[i] !== undefined) {
  59277. types.push(options.types[i]);
  59278. }
  59279. else {
  59280. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59281. }
  59282. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  59283. samplingModes.push(options.samplingModes[i]);
  59284. }
  59285. else {
  59286. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59287. }
  59288. }
  59289. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  59290. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  59291. _this._size = size;
  59292. _this._multiRenderTargetOptions = {
  59293. samplingModes: samplingModes,
  59294. generateMipMaps: generateMipMaps,
  59295. generateDepthBuffer: generateDepthBuffer,
  59296. generateStencilBuffer: generateStencilBuffer,
  59297. generateDepthTexture: generateDepthTexture,
  59298. types: types,
  59299. textureCount: count
  59300. };
  59301. _this._createInternalTextures();
  59302. _this._createTextures();
  59303. return _this;
  59304. }
  59305. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  59306. get: function () {
  59307. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  59308. },
  59309. enumerable: true,
  59310. configurable: true
  59311. });
  59312. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  59313. get: function () {
  59314. return this._textures;
  59315. },
  59316. enumerable: true,
  59317. configurable: true
  59318. });
  59319. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  59320. get: function () {
  59321. return this._textures[this._textures.length - 1];
  59322. },
  59323. enumerable: true,
  59324. configurable: true
  59325. });
  59326. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  59327. set: function (wrap) {
  59328. if (this._textures) {
  59329. for (var i = 0; i < this._textures.length; i++) {
  59330. this._textures[i].wrapU = wrap;
  59331. }
  59332. }
  59333. },
  59334. enumerable: true,
  59335. configurable: true
  59336. });
  59337. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  59338. set: function (wrap) {
  59339. if (this._textures) {
  59340. for (var i = 0; i < this._textures.length; i++) {
  59341. this._textures[i].wrapV = wrap;
  59342. }
  59343. }
  59344. },
  59345. enumerable: true,
  59346. configurable: true
  59347. });
  59348. MultiRenderTarget.prototype._rebuild = function () {
  59349. this.releaseInternalTextures();
  59350. this._createInternalTextures();
  59351. for (var i = 0; i < this._internalTextures.length; i++) {
  59352. var texture = this._textures[i];
  59353. texture._texture = this._internalTextures[i];
  59354. }
  59355. // Keeps references to frame buffer and stencil/depth buffer
  59356. this._texture = this._internalTextures[0];
  59357. };
  59358. MultiRenderTarget.prototype._createInternalTextures = function () {
  59359. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  59360. };
  59361. MultiRenderTarget.prototype._createTextures = function () {
  59362. this._textures = [];
  59363. for (var i = 0; i < this._internalTextures.length; i++) {
  59364. var texture = new BABYLON.Texture(null, this.getScene());
  59365. texture._texture = this._internalTextures[i];
  59366. this._textures.push(texture);
  59367. }
  59368. // Keeps references to frame buffer and stencil/depth buffer
  59369. this._texture = this._internalTextures[0];
  59370. };
  59371. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  59372. get: function () {
  59373. return this._samples;
  59374. },
  59375. set: function (value) {
  59376. if (this._samples === value) {
  59377. return;
  59378. }
  59379. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  59380. },
  59381. enumerable: true,
  59382. configurable: true
  59383. });
  59384. MultiRenderTarget.prototype.resize = function (size) {
  59385. this.releaseInternalTextures();
  59386. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  59387. this._createInternalTextures();
  59388. };
  59389. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  59390. var _this = this;
  59391. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  59392. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  59393. });
  59394. };
  59395. MultiRenderTarget.prototype.dispose = function () {
  59396. this.releaseInternalTextures();
  59397. _super.prototype.dispose.call(this);
  59398. };
  59399. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  59400. if (!this._internalTextures) {
  59401. return;
  59402. }
  59403. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  59404. if (this._internalTextures[i] !== undefined) {
  59405. this._internalTextures[i].dispose();
  59406. this._internalTextures.splice(i, 1);
  59407. }
  59408. }
  59409. };
  59410. return MultiRenderTarget;
  59411. }(BABYLON.RenderTargetTexture));
  59412. BABYLON.MultiRenderTarget = MultiRenderTarget;
  59413. })(BABYLON || (BABYLON = {}));
  59414. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  59415. var BABYLON;
  59416. (function (BABYLON) {
  59417. var MirrorTexture = /** @class */ (function (_super) {
  59418. __extends(MirrorTexture, _super);
  59419. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  59420. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59421. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59422. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  59423. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  59424. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  59425. _this._transformMatrix = BABYLON.Matrix.Zero();
  59426. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  59427. _this._adaptiveBlurKernel = 0;
  59428. _this._blurKernelX = 0;
  59429. _this._blurKernelY = 0;
  59430. _this._blurRatio = 1.0;
  59431. _this.ignoreCameraViewport = true;
  59432. _this.onBeforeRenderObservable.add(function () {
  59433. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  59434. _this._savedViewMatrix = scene.getViewMatrix();
  59435. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  59436. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  59437. scene.clipPlane = _this.mirrorPlane;
  59438. scene.getEngine().cullBackFaces = false;
  59439. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  59440. });
  59441. _this.onAfterRenderObservable.add(function () {
  59442. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  59443. scene.getEngine().cullBackFaces = true;
  59444. scene._mirroredCameraPosition = null;
  59445. delete scene.clipPlane;
  59446. });
  59447. return _this;
  59448. }
  59449. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  59450. get: function () {
  59451. return this._blurRatio;
  59452. },
  59453. set: function (value) {
  59454. if (this._blurRatio === value) {
  59455. return;
  59456. }
  59457. this._blurRatio = value;
  59458. this._preparePostProcesses();
  59459. },
  59460. enumerable: true,
  59461. configurable: true
  59462. });
  59463. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  59464. set: function (value) {
  59465. this._adaptiveBlurKernel = value;
  59466. this._autoComputeBlurKernel();
  59467. },
  59468. enumerable: true,
  59469. configurable: true
  59470. });
  59471. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  59472. set: function (value) {
  59473. this.blurKernelX = value;
  59474. this.blurKernelY = value;
  59475. },
  59476. enumerable: true,
  59477. configurable: true
  59478. });
  59479. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  59480. get: function () {
  59481. return this._blurKernelX;
  59482. },
  59483. set: function (value) {
  59484. if (this._blurKernelX === value) {
  59485. return;
  59486. }
  59487. this._blurKernelX = value;
  59488. this._preparePostProcesses();
  59489. },
  59490. enumerable: true,
  59491. configurable: true
  59492. });
  59493. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  59494. get: function () {
  59495. return this._blurKernelY;
  59496. },
  59497. set: function (value) {
  59498. if (this._blurKernelY === value) {
  59499. return;
  59500. }
  59501. this._blurKernelY = value;
  59502. this._preparePostProcesses();
  59503. },
  59504. enumerable: true,
  59505. configurable: true
  59506. });
  59507. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  59508. var engine = this.getScene().getEngine();
  59509. var dw = this.getRenderWidth() / engine.getRenderWidth();
  59510. var dh = this.getRenderHeight() / engine.getRenderHeight();
  59511. this.blurKernelX = this._adaptiveBlurKernel * dw;
  59512. this.blurKernelY = this._adaptiveBlurKernel * dh;
  59513. };
  59514. MirrorTexture.prototype._onRatioRescale = function () {
  59515. if (this._sizeRatio) {
  59516. this.resize(this._initialSizeParameter);
  59517. if (!this._adaptiveBlurKernel) {
  59518. this._preparePostProcesses();
  59519. }
  59520. }
  59521. if (this._adaptiveBlurKernel) {
  59522. this._autoComputeBlurKernel();
  59523. }
  59524. };
  59525. MirrorTexture.prototype._preparePostProcesses = function () {
  59526. this.clearPostProcesses(true);
  59527. if (this._blurKernelX && this._blurKernelY) {
  59528. var engine = this.getScene().getEngine();
  59529. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59530. 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);
  59531. this._blurX.autoClear = false;
  59532. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  59533. this._blurX.inputTexture = this._texture;
  59534. }
  59535. else {
  59536. this._blurX.alwaysForcePOT = true;
  59537. }
  59538. 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);
  59539. this._blurY.autoClear = false;
  59540. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  59541. this.addPostProcess(this._blurX);
  59542. this.addPostProcess(this._blurY);
  59543. }
  59544. else {
  59545. if (this._blurY) {
  59546. this.removePostProcess(this._blurY);
  59547. this._blurY.dispose();
  59548. this._blurY = null;
  59549. }
  59550. if (this._blurX) {
  59551. this.removePostProcess(this._blurX);
  59552. this._blurX.dispose();
  59553. this._blurX = null;
  59554. }
  59555. }
  59556. };
  59557. MirrorTexture.prototype.clone = function () {
  59558. var scene = this.getScene();
  59559. if (!scene) {
  59560. return this;
  59561. }
  59562. var textureSize = this.getSize();
  59563. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  59564. // Base texture
  59565. newTexture.hasAlpha = this.hasAlpha;
  59566. newTexture.level = this.level;
  59567. // Mirror Texture
  59568. newTexture.mirrorPlane = this.mirrorPlane.clone();
  59569. if (this.renderList) {
  59570. newTexture.renderList = this.renderList.slice(0);
  59571. }
  59572. return newTexture;
  59573. };
  59574. MirrorTexture.prototype.serialize = function () {
  59575. if (!this.name) {
  59576. return null;
  59577. }
  59578. var serializationObject = _super.prototype.serialize.call(this);
  59579. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  59580. return serializationObject;
  59581. };
  59582. return MirrorTexture;
  59583. }(BABYLON.RenderTargetTexture));
  59584. BABYLON.MirrorTexture = MirrorTexture;
  59585. })(BABYLON || (BABYLON = {}));
  59586. //# sourceMappingURL=babylon.mirrorTexture.js.map
  59587. var BABYLON;
  59588. (function (BABYLON) {
  59589. /**
  59590. * Creates a refraction texture used by refraction channel of the standard material.
  59591. * @param name the texture name
  59592. * @param size size of the underlying texture
  59593. * @param scene root scene
  59594. */
  59595. var RefractionTexture = /** @class */ (function (_super) {
  59596. __extends(RefractionTexture, _super);
  59597. function RefractionTexture(name, size, scene, generateMipMaps) {
  59598. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  59599. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  59600. _this.depth = 2.0;
  59601. _this.onBeforeRenderObservable.add(function () {
  59602. scene.clipPlane = _this.refractionPlane;
  59603. });
  59604. _this.onAfterRenderObservable.add(function () {
  59605. delete scene.clipPlane;
  59606. });
  59607. return _this;
  59608. }
  59609. RefractionTexture.prototype.clone = function () {
  59610. var scene = this.getScene();
  59611. if (!scene) {
  59612. return this;
  59613. }
  59614. var textureSize = this.getSize();
  59615. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  59616. // Base texture
  59617. newTexture.hasAlpha = this.hasAlpha;
  59618. newTexture.level = this.level;
  59619. // Refraction Texture
  59620. newTexture.refractionPlane = this.refractionPlane.clone();
  59621. if (this.renderList) {
  59622. newTexture.renderList = this.renderList.slice(0);
  59623. }
  59624. newTexture.depth = this.depth;
  59625. return newTexture;
  59626. };
  59627. RefractionTexture.prototype.serialize = function () {
  59628. if (!this.name) {
  59629. return null;
  59630. }
  59631. var serializationObject = _super.prototype.serialize.call(this);
  59632. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  59633. serializationObject.depth = this.depth;
  59634. return serializationObject;
  59635. };
  59636. return RefractionTexture;
  59637. }(BABYLON.RenderTargetTexture));
  59638. BABYLON.RefractionTexture = RefractionTexture;
  59639. })(BABYLON || (BABYLON = {}));
  59640. //# sourceMappingURL=babylon.refractionTexture.js.map
  59641. var BABYLON;
  59642. (function (BABYLON) {
  59643. var DynamicTexture = /** @class */ (function (_super) {
  59644. __extends(DynamicTexture, _super);
  59645. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  59646. if (scene === void 0) { scene = null; }
  59647. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59648. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  59649. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  59650. _this.name = name;
  59651. _this._engine = _this.getScene().getEngine();
  59652. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59653. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59654. _this._generateMipMaps = generateMipMaps;
  59655. if (options.getContext) {
  59656. _this._canvas = options;
  59657. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  59658. }
  59659. else {
  59660. _this._canvas = document.createElement("canvas");
  59661. if (options.width) {
  59662. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  59663. }
  59664. else {
  59665. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  59666. }
  59667. }
  59668. var textureSize = _this.getSize();
  59669. _this._canvas.width = textureSize.width;
  59670. _this._canvas.height = textureSize.height;
  59671. _this._context = _this._canvas.getContext("2d");
  59672. return _this;
  59673. }
  59674. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  59675. get: function () {
  59676. return true;
  59677. },
  59678. enumerable: true,
  59679. configurable: true
  59680. });
  59681. DynamicTexture.prototype._recreate = function (textureSize) {
  59682. this._canvas.width = textureSize.width;
  59683. this._canvas.height = textureSize.height;
  59684. this.releaseInternalTexture();
  59685. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  59686. };
  59687. DynamicTexture.prototype.scale = function (ratio) {
  59688. var textureSize = this.getSize();
  59689. textureSize.width *= ratio;
  59690. textureSize.height *= ratio;
  59691. this._recreate(textureSize);
  59692. };
  59693. DynamicTexture.prototype.scaleTo = function (width, height) {
  59694. var textureSize = this.getSize();
  59695. textureSize.width = width;
  59696. textureSize.height = height;
  59697. this._recreate(textureSize);
  59698. };
  59699. DynamicTexture.prototype.getContext = function () {
  59700. return this._context;
  59701. };
  59702. DynamicTexture.prototype.clear = function () {
  59703. var size = this.getSize();
  59704. this._context.fillRect(0, 0, size.width, size.height);
  59705. };
  59706. DynamicTexture.prototype.update = function (invertY) {
  59707. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  59708. };
  59709. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  59710. if (update === void 0) { update = true; }
  59711. var size = this.getSize();
  59712. if (clearColor) {
  59713. this._context.fillStyle = clearColor;
  59714. this._context.fillRect(0, 0, size.width, size.height);
  59715. }
  59716. this._context.font = font;
  59717. if (x === null || x === undefined) {
  59718. var textSize = this._context.measureText(text);
  59719. x = (size.width - textSize.width) / 2;
  59720. }
  59721. if (y === null || y === undefined) {
  59722. var fontSize = parseInt((font.replace(/\D/g, '')));
  59723. ;
  59724. y = (size.height / 2) + (fontSize / 3.65);
  59725. }
  59726. this._context.fillStyle = color;
  59727. this._context.fillText(text, x, y);
  59728. if (update) {
  59729. this.update(invertY);
  59730. }
  59731. };
  59732. DynamicTexture.prototype.clone = function () {
  59733. var scene = this.getScene();
  59734. if (!scene) {
  59735. return this;
  59736. }
  59737. var textureSize = this.getSize();
  59738. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  59739. // Base texture
  59740. newTexture.hasAlpha = this.hasAlpha;
  59741. newTexture.level = this.level;
  59742. // Dynamic Texture
  59743. newTexture.wrapU = this.wrapU;
  59744. newTexture.wrapV = this.wrapV;
  59745. return newTexture;
  59746. };
  59747. DynamicTexture.prototype._rebuild = function () {
  59748. this.update();
  59749. };
  59750. return DynamicTexture;
  59751. }(BABYLON.Texture));
  59752. BABYLON.DynamicTexture = DynamicTexture;
  59753. })(BABYLON || (BABYLON = {}));
  59754. //# sourceMappingURL=babylon.dynamicTexture.js.map
  59755. var BABYLON;
  59756. (function (BABYLON) {
  59757. var VideoTexture = /** @class */ (function (_super) {
  59758. __extends(VideoTexture, _super);
  59759. /**
  59760. * Creates a video texture.
  59761. * Sample : https://doc.babylonjs.com/how_to/video_texture
  59762. * @param {string | null} name optional name, will detect from video source, if not defined
  59763. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  59764. * @param {BABYLON.Scene} scene is obviously the current scene.
  59765. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  59766. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  59767. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  59768. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  59769. */
  59770. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  59771. if (generateMipMaps === void 0) { generateMipMaps = false; }
  59772. if (invertY === void 0) { invertY = false; }
  59773. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59774. if (settings === void 0) { settings = {
  59775. autoPlay: true,
  59776. loop: true,
  59777. autoUpdateTexture: true,
  59778. }; }
  59779. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  59780. _this._createInternalTexture = function () {
  59781. if (_this._texture != null) {
  59782. return;
  59783. }
  59784. if (!_this._engine.needPOTTextures ||
  59785. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  59786. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  59787. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  59788. }
  59789. else {
  59790. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59791. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59792. _this._generateMipMaps = false;
  59793. }
  59794. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  59795. _this._texture.isReady = true;
  59796. _this._updateInternalTexture();
  59797. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  59798. _this.onLoadObservable.notifyObservers(_this);
  59799. }
  59800. };
  59801. _this.reset = function () {
  59802. if (_this._texture == null) {
  59803. return;
  59804. }
  59805. _this._texture.dispose();
  59806. _this._texture = null;
  59807. };
  59808. _this._updateInternalTexture = function (e) {
  59809. if (_this._texture == null || !_this._texture.isReady) {
  59810. return;
  59811. }
  59812. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  59813. return;
  59814. }
  59815. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  59816. };
  59817. _this._engine = _this.getScene().getEngine();
  59818. _this._generateMipMaps = generateMipMaps;
  59819. _this._samplingMode = samplingMode;
  59820. _this.autoUpdateTexture = settings.autoUpdateTexture;
  59821. _this.name = name || _this._getName(src);
  59822. _this.video = _this._getVideo(src);
  59823. if (settings.autoPlay !== undefined) {
  59824. _this.video.autoplay = settings.autoPlay;
  59825. }
  59826. if (settings.loop !== undefined) {
  59827. _this.video.loop = settings.loop;
  59828. }
  59829. _this.video.addEventListener("canplay", _this._createInternalTexture);
  59830. _this.video.addEventListener("paused", _this._updateInternalTexture);
  59831. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  59832. _this.video.addEventListener("emptied", _this.reset);
  59833. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  59834. _this._createInternalTexture();
  59835. }
  59836. return _this;
  59837. }
  59838. VideoTexture.prototype._getName = function (src) {
  59839. if (src instanceof HTMLVideoElement) {
  59840. return src.currentSrc;
  59841. }
  59842. if (typeof src === "object") {
  59843. return src.toString();
  59844. }
  59845. return src;
  59846. };
  59847. ;
  59848. VideoTexture.prototype._getVideo = function (src) {
  59849. if (src instanceof HTMLVideoElement) {
  59850. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  59851. return src;
  59852. }
  59853. var video = document.createElement("video");
  59854. if (typeof src === "string") {
  59855. BABYLON.Tools.SetCorsBehavior(src, video);
  59856. video.src = src;
  59857. }
  59858. else {
  59859. BABYLON.Tools.SetCorsBehavior(src[0], video);
  59860. src.forEach(function (url) {
  59861. var source = document.createElement("source");
  59862. source.src = url;
  59863. video.appendChild(source);
  59864. });
  59865. }
  59866. return video;
  59867. };
  59868. ;
  59869. /**
  59870. * Internal method to initiate `update`.
  59871. */
  59872. VideoTexture.prototype._rebuild = function () {
  59873. this.update();
  59874. };
  59875. /**
  59876. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  59877. */
  59878. VideoTexture.prototype.update = function () {
  59879. if (!this.autoUpdateTexture) {
  59880. // Expecting user to call `updateTexture` manually
  59881. return;
  59882. }
  59883. this.updateTexture(true);
  59884. };
  59885. /**
  59886. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  59887. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  59888. */
  59889. VideoTexture.prototype.updateTexture = function (isVisible) {
  59890. if (!isVisible) {
  59891. return;
  59892. }
  59893. if (this.video.paused) {
  59894. return;
  59895. }
  59896. this._updateInternalTexture();
  59897. };
  59898. /**
  59899. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  59900. * @param url New url.
  59901. */
  59902. VideoTexture.prototype.updateURL = function (url) {
  59903. this.video.src = url;
  59904. };
  59905. VideoTexture.prototype.dispose = function () {
  59906. _super.prototype.dispose.call(this);
  59907. this.video.removeEventListener("canplay", this._createInternalTexture);
  59908. this.video.removeEventListener("paused", this._updateInternalTexture);
  59909. this.video.removeEventListener("seeked", this._updateInternalTexture);
  59910. this.video.removeEventListener("emptied", this.reset);
  59911. this.video.pause();
  59912. };
  59913. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  59914. var video = document.createElement("video");
  59915. var constraintsDeviceId;
  59916. if (constraints && constraints.deviceId) {
  59917. constraintsDeviceId = {
  59918. exact: constraints.deviceId,
  59919. };
  59920. }
  59921. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  59922. if (navigator.mediaDevices) {
  59923. navigator.mediaDevices.getUserMedia({ video: constraints })
  59924. .then(function (stream) {
  59925. if (video.mozSrcObject !== undefined) {
  59926. // hack for Firefox < 19
  59927. video.mozSrcObject = stream;
  59928. }
  59929. else {
  59930. video.srcObject = stream;
  59931. }
  59932. var onPlaying = function () {
  59933. if (onReady) {
  59934. onReady(new VideoTexture("video", video, scene, true, true));
  59935. }
  59936. video.removeEventListener("playing", onPlaying);
  59937. };
  59938. video.addEventListener("playing", onPlaying);
  59939. video.play();
  59940. })
  59941. .catch(function (err) {
  59942. BABYLON.Tools.Error(err.name);
  59943. });
  59944. }
  59945. else {
  59946. navigator.getUserMedia =
  59947. navigator.getUserMedia ||
  59948. navigator.webkitGetUserMedia ||
  59949. navigator.mozGetUserMedia ||
  59950. navigator.msGetUserMedia;
  59951. if (navigator.getUserMedia) {
  59952. navigator.getUserMedia({
  59953. video: {
  59954. deviceId: constraintsDeviceId,
  59955. width: {
  59956. min: (constraints && constraints.minWidth) || 256,
  59957. max: (constraints && constraints.maxWidth) || 640,
  59958. },
  59959. height: {
  59960. min: (constraints && constraints.minHeight) || 256,
  59961. max: (constraints && constraints.maxHeight) || 480,
  59962. },
  59963. },
  59964. }, function (stream) {
  59965. if (video.mozSrcObject !== undefined) {
  59966. // hack for Firefox < 19
  59967. video.mozSrcObject = stream;
  59968. }
  59969. else {
  59970. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  59971. }
  59972. video.play();
  59973. if (onReady) {
  59974. onReady(new VideoTexture("video", video, scene, true, true));
  59975. }
  59976. }, function (e) {
  59977. BABYLON.Tools.Error(e.name);
  59978. });
  59979. }
  59980. }
  59981. };
  59982. return VideoTexture;
  59983. }(BABYLON.Texture));
  59984. BABYLON.VideoTexture = VideoTexture;
  59985. })(BABYLON || (BABYLON = {}));
  59986. //# sourceMappingURL=babylon.videoTexture.js.map
  59987. var BABYLON;
  59988. (function (BABYLON) {
  59989. var RawTexture = /** @class */ (function (_super) {
  59990. __extends(RawTexture, _super);
  59991. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  59992. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59993. if (invertY === void 0) { invertY = false; }
  59994. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59995. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59996. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  59997. _this.format = format;
  59998. _this._engine = scene.getEngine();
  59999. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  60000. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60001. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60002. return _this;
  60003. }
  60004. RawTexture.prototype.update = function (data) {
  60005. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  60006. };
  60007. // Statics
  60008. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60009. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60010. if (invertY === void 0) { invertY = false; }
  60011. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60012. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  60013. };
  60014. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60015. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60016. if (invertY === void 0) { invertY = false; }
  60017. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60018. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  60019. };
  60020. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60021. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60022. if (invertY === void 0) { invertY = false; }
  60023. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60024. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  60025. };
  60026. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  60027. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60028. if (invertY === void 0) { invertY = false; }
  60029. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60030. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60031. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  60032. };
  60033. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  60034. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60035. if (invertY === void 0) { invertY = false; }
  60036. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60037. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60038. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  60039. };
  60040. return RawTexture;
  60041. }(BABYLON.Texture));
  60042. BABYLON.RawTexture = RawTexture;
  60043. })(BABYLON || (BABYLON = {}));
  60044. //# sourceMappingURL=babylon.rawTexture.js.map
  60045. var BABYLON;
  60046. (function (BABYLON) {
  60047. /**
  60048. * PostProcess can be used to apply a shader to a texture after it has been rendered
  60049. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  60050. */
  60051. var PostProcess = /** @class */ (function () {
  60052. /**
  60053. * Creates a new instance of @see PostProcess
  60054. * @param name The name of the PostProcess.
  60055. * @param fragmentUrl The url of the fragment shader to be used.
  60056. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  60057. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  60058. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  60059. * @param camera The camera to apply the render pass to.
  60060. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  60061. * @param engine The engine which the post process will be applied. (default: current engine)
  60062. * @param reusable If the post process can be reused on the same frame. (default: false)
  60063. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  60064. * @param textureType Type of textures used when performing the post process. (default: 0)
  60065. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  60066. * @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
  60067. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  60068. */
  60069. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  60070. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  60071. if (defines === void 0) { defines = null; }
  60072. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60073. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  60074. if (blockCompilation === void 0) { blockCompilation = false; }
  60075. this.name = name;
  60076. /**
  60077. * Width of the texture to apply the post process on
  60078. */
  60079. this.width = -1;
  60080. /**
  60081. * Height of the texture to apply the post process on
  60082. */
  60083. this.height = -1;
  60084. /**
  60085. * If the buffer needs to be cleared before applying the post process. (default: true)
  60086. * Should be set to false if shader will overwrite all previous pixels.
  60087. */
  60088. this.autoClear = true;
  60089. /**
  60090. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  60091. */
  60092. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  60093. /**
  60094. * Animations to be used for the post processing
  60095. */
  60096. this.animations = new Array();
  60097. /**
  60098. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  60099. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  60100. */
  60101. this.enablePixelPerfectMode = false;
  60102. /**
  60103. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  60104. */
  60105. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  60106. /**
  60107. * Force textures to be a power of two (default: false)
  60108. */
  60109. this.alwaysForcePOT = false;
  60110. /**
  60111. * Number of sample textures (default: 1)
  60112. */
  60113. this.samples = 1;
  60114. /**
  60115. * Modify the scale of the post process to be the same as the viewport (default: false)
  60116. */
  60117. this.adaptScaleToCurrentViewport = false;
  60118. this._reusable = false;
  60119. /**
  60120. * Smart array of input and output textures for the post process.
  60121. */
  60122. this._textures = new BABYLON.SmartArray(2);
  60123. /**
  60124. * The index in _textures that corresponds to the output texture.
  60125. */
  60126. this._currentRenderTextureInd = 0;
  60127. this._scaleRatio = new BABYLON.Vector2(1, 1);
  60128. this._texelSize = BABYLON.Vector2.Zero();
  60129. // Events
  60130. /**
  60131. * An event triggered when the postprocess is activated.
  60132. * @type {BABYLON.Observable}
  60133. */
  60134. this.onActivateObservable = new BABYLON.Observable();
  60135. /**
  60136. * An event triggered when the postprocess changes its size.
  60137. * @type {BABYLON.Observable}
  60138. */
  60139. this.onSizeChangedObservable = new BABYLON.Observable();
  60140. /**
  60141. * An event triggered when the postprocess applies its effect.
  60142. * @type {BABYLON.Observable}
  60143. */
  60144. this.onApplyObservable = new BABYLON.Observable();
  60145. /**
  60146. * An event triggered before rendering the postprocess
  60147. * @type {BABYLON.Observable}
  60148. */
  60149. this.onBeforeRenderObservable = new BABYLON.Observable();
  60150. /**
  60151. * An event triggered after rendering the postprocess
  60152. * @type {BABYLON.Observable}
  60153. */
  60154. this.onAfterRenderObservable = new BABYLON.Observable();
  60155. if (camera != null) {
  60156. this._camera = camera;
  60157. this._scene = camera.getScene();
  60158. camera.attachPostProcess(this);
  60159. this._engine = this._scene.getEngine();
  60160. this._scene.postProcesses.push(this);
  60161. }
  60162. else if (engine) {
  60163. this._engine = engine;
  60164. this._engine.postProcesses.push(this);
  60165. }
  60166. this._options = options;
  60167. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  60168. this._reusable = reusable || false;
  60169. this._textureType = textureType;
  60170. this._samplers = samplers || [];
  60171. this._samplers.push("textureSampler");
  60172. this._fragmentUrl = fragmentUrl;
  60173. this._vertexUrl = vertexUrl;
  60174. this._parameters = parameters || [];
  60175. this._parameters.push("scale");
  60176. this._indexParameters = indexParameters;
  60177. if (!blockCompilation) {
  60178. this.updateEffect(defines);
  60179. }
  60180. }
  60181. Object.defineProperty(PostProcess.prototype, "onActivate", {
  60182. /**
  60183. * A function that is added to the onActivateObservable
  60184. */
  60185. set: function (callback) {
  60186. if (this._onActivateObserver) {
  60187. this.onActivateObservable.remove(this._onActivateObserver);
  60188. }
  60189. if (callback) {
  60190. this._onActivateObserver = this.onActivateObservable.add(callback);
  60191. }
  60192. },
  60193. enumerable: true,
  60194. configurable: true
  60195. });
  60196. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  60197. /**
  60198. * A function that is added to the onSizeChangedObservable
  60199. */
  60200. set: function (callback) {
  60201. if (this._onSizeChangedObserver) {
  60202. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  60203. }
  60204. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  60205. },
  60206. enumerable: true,
  60207. configurable: true
  60208. });
  60209. Object.defineProperty(PostProcess.prototype, "onApply", {
  60210. /**
  60211. * A function that is added to the onApplyObservable
  60212. */
  60213. set: function (callback) {
  60214. if (this._onApplyObserver) {
  60215. this.onApplyObservable.remove(this._onApplyObserver);
  60216. }
  60217. this._onApplyObserver = this.onApplyObservable.add(callback);
  60218. },
  60219. enumerable: true,
  60220. configurable: true
  60221. });
  60222. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  60223. /**
  60224. * A function that is added to the onBeforeRenderObservable
  60225. */
  60226. set: function (callback) {
  60227. if (this._onBeforeRenderObserver) {
  60228. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  60229. }
  60230. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  60231. },
  60232. enumerable: true,
  60233. configurable: true
  60234. });
  60235. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  60236. /**
  60237. * A function that is added to the onAfterRenderObservable
  60238. */
  60239. set: function (callback) {
  60240. if (this._onAfterRenderObserver) {
  60241. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  60242. }
  60243. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  60244. },
  60245. enumerable: true,
  60246. configurable: true
  60247. });
  60248. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  60249. /**
  60250. * 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
  60251. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  60252. */
  60253. get: function () {
  60254. return this._textures.data[this._currentRenderTextureInd];
  60255. },
  60256. set: function (value) {
  60257. this._forcedOutputTexture = value;
  60258. },
  60259. enumerable: true,
  60260. configurable: true
  60261. });
  60262. /**
  60263. * Gets the camera which post process is applied to.
  60264. * @returns The camera the post process is applied to.
  60265. */
  60266. PostProcess.prototype.getCamera = function () {
  60267. return this._camera;
  60268. };
  60269. Object.defineProperty(PostProcess.prototype, "texelSize", {
  60270. /**
  60271. * Gets the texel size of the postprocess.
  60272. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  60273. */
  60274. get: function () {
  60275. if (this._shareOutputWithPostProcess) {
  60276. return this._shareOutputWithPostProcess.texelSize;
  60277. }
  60278. if (this._forcedOutputTexture) {
  60279. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  60280. }
  60281. return this._texelSize;
  60282. },
  60283. enumerable: true,
  60284. configurable: true
  60285. });
  60286. /**
  60287. * Gets the engine which this post process belongs to.
  60288. * @returns The engine the post process was enabled with.
  60289. */
  60290. PostProcess.prototype.getEngine = function () {
  60291. return this._engine;
  60292. };
  60293. /**
  60294. * The effect that is created when initializing the post process.
  60295. * @returns The created effect corrisponding the the postprocess.
  60296. */
  60297. PostProcess.prototype.getEffect = function () {
  60298. return this._effect;
  60299. };
  60300. /**
  60301. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  60302. * @param postProcess The post process to share the output with.
  60303. * @returns This post process.
  60304. */
  60305. PostProcess.prototype.shareOutputWith = function (postProcess) {
  60306. this._disposeTextures();
  60307. this._shareOutputWithPostProcess = postProcess;
  60308. return this;
  60309. };
  60310. /**
  60311. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  60312. * This should be called if the post process that shares output with this post process is disabled/disposed.
  60313. */
  60314. PostProcess.prototype.useOwnOutput = function () {
  60315. if (this._textures.length == 0) {
  60316. this._textures = new BABYLON.SmartArray(2);
  60317. }
  60318. this._shareOutputWithPostProcess = null;
  60319. };
  60320. /**
  60321. * Updates the effect with the current post process compile time values and recompiles the shader.
  60322. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  60323. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  60324. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  60325. * @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
  60326. * @param onCompiled Called when the shader has been compiled.
  60327. * @param onError Called if there is an error when compiling a shader.
  60328. */
  60329. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  60330. if (defines === void 0) { defines = null; }
  60331. if (uniforms === void 0) { uniforms = null; }
  60332. if (samplers === void 0) { samplers = null; }
  60333. 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);
  60334. };
  60335. /**
  60336. * The post process is reusable if it can be used multiple times within one frame.
  60337. * @returns If the post process is reusable
  60338. */
  60339. PostProcess.prototype.isReusable = function () {
  60340. return this._reusable;
  60341. };
  60342. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  60343. PostProcess.prototype.markTextureDirty = function () {
  60344. this.width = -1;
  60345. };
  60346. /**
  60347. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  60348. * 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.
  60349. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  60350. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  60351. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  60352. */
  60353. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  60354. var _this = this;
  60355. if (sourceTexture === void 0) { sourceTexture = null; }
  60356. camera = camera || this._camera;
  60357. var scene = camera.getScene();
  60358. var engine = scene.getEngine();
  60359. var maxSize = engine.getCaps().maxTextureSize;
  60360. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  60361. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  60362. // 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
  60363. var webVRCamera = camera.parent;
  60364. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  60365. requiredWidth /= 2;
  60366. }
  60367. var desiredWidth = (this._options.width || requiredWidth);
  60368. var desiredHeight = this._options.height || requiredHeight;
  60369. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  60370. if (this.adaptScaleToCurrentViewport) {
  60371. var currentViewport = engine.currentViewport;
  60372. if (currentViewport) {
  60373. desiredWidth *= currentViewport.width;
  60374. desiredHeight *= currentViewport.height;
  60375. }
  60376. }
  60377. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  60378. if (!this._options.width) {
  60379. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  60380. }
  60381. if (!this._options.height) {
  60382. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  60383. }
  60384. }
  60385. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  60386. if (this._textures.length > 0) {
  60387. for (var i = 0; i < this._textures.length; i++) {
  60388. this._engine._releaseTexture(this._textures.data[i]);
  60389. }
  60390. this._textures.reset();
  60391. }
  60392. this.width = desiredWidth;
  60393. this.height = desiredHeight;
  60394. var textureSize = { width: this.width, height: this.height };
  60395. var textureOptions = {
  60396. generateMipMaps: false,
  60397. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  60398. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  60399. samplingMode: this.renderTargetSamplingMode,
  60400. type: this._textureType
  60401. };
  60402. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  60403. if (this._reusable) {
  60404. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  60405. }
  60406. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  60407. this.onSizeChangedObservable.notifyObservers(this);
  60408. }
  60409. this._textures.forEach(function (texture) {
  60410. if (texture.samples !== _this.samples) {
  60411. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  60412. }
  60413. });
  60414. }
  60415. var target;
  60416. if (this._shareOutputWithPostProcess) {
  60417. target = this._shareOutputWithPostProcess.inputTexture;
  60418. }
  60419. else if (this._forcedOutputTexture) {
  60420. target = this._forcedOutputTexture;
  60421. this.width = this._forcedOutputTexture.width;
  60422. this.height = this._forcedOutputTexture.height;
  60423. }
  60424. else {
  60425. target = this.inputTexture;
  60426. }
  60427. // Bind the input of this post process to be used as the output of the previous post process.
  60428. if (this.enablePixelPerfectMode) {
  60429. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  60430. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  60431. }
  60432. else {
  60433. this._scaleRatio.copyFromFloats(1, 1);
  60434. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  60435. }
  60436. this.onActivateObservable.notifyObservers(camera);
  60437. // Clear
  60438. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  60439. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  60440. }
  60441. if (this._reusable) {
  60442. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  60443. }
  60444. };
  60445. Object.defineProperty(PostProcess.prototype, "isSupported", {
  60446. /**
  60447. * If the post process is supported.
  60448. */
  60449. get: function () {
  60450. return this._effect.isSupported;
  60451. },
  60452. enumerable: true,
  60453. configurable: true
  60454. });
  60455. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  60456. /**
  60457. * The aspect ratio of the output texture.
  60458. */
  60459. get: function () {
  60460. if (this._shareOutputWithPostProcess) {
  60461. return this._shareOutputWithPostProcess.aspectRatio;
  60462. }
  60463. if (this._forcedOutputTexture) {
  60464. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  60465. }
  60466. return this.width / this.height;
  60467. },
  60468. enumerable: true,
  60469. configurable: true
  60470. });
  60471. /**
  60472. * Get a value indicating if the post-process is ready to be used
  60473. * @returns true if the post-process is ready (shader is compiled)
  60474. */
  60475. PostProcess.prototype.isReady = function () {
  60476. return this._effect && this._effect.isReady();
  60477. };
  60478. /**
  60479. * Binds all textures and uniforms to the shader, this will be run on every pass.
  60480. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  60481. */
  60482. PostProcess.prototype.apply = function () {
  60483. // Check
  60484. if (!this._effect || !this._effect.isReady())
  60485. return null;
  60486. // States
  60487. this._engine.enableEffect(this._effect);
  60488. this._engine.setState(false);
  60489. this._engine.setDepthBuffer(false);
  60490. this._engine.setDepthWrite(false);
  60491. // Alpha
  60492. this._engine.setAlphaMode(this.alphaMode);
  60493. if (this.alphaConstants) {
  60494. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  60495. }
  60496. // Bind the output texture of the preivous post process as the input to this post process.
  60497. var source;
  60498. if (this._shareOutputWithPostProcess) {
  60499. source = this._shareOutputWithPostProcess.inputTexture;
  60500. }
  60501. else if (this._forcedOutputTexture) {
  60502. source = this._forcedOutputTexture;
  60503. }
  60504. else {
  60505. source = this.inputTexture;
  60506. }
  60507. this._effect._bindTexture("textureSampler", source);
  60508. // Parameters
  60509. this._effect.setVector2("scale", this._scaleRatio);
  60510. this.onApplyObservable.notifyObservers(this._effect);
  60511. return this._effect;
  60512. };
  60513. PostProcess.prototype._disposeTextures = function () {
  60514. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  60515. return;
  60516. }
  60517. if (this._textures.length > 0) {
  60518. for (var i = 0; i < this._textures.length; i++) {
  60519. this._engine._releaseTexture(this._textures.data[i]);
  60520. }
  60521. }
  60522. this._textures.dispose();
  60523. };
  60524. /**
  60525. * Disposes the post process.
  60526. * @param camera The camera to dispose the post process on.
  60527. */
  60528. PostProcess.prototype.dispose = function (camera) {
  60529. camera = camera || this._camera;
  60530. this._disposeTextures();
  60531. if (this._scene) {
  60532. var index_1 = this._scene.postProcesses.indexOf(this);
  60533. if (index_1 !== -1) {
  60534. this._scene.postProcesses.splice(index_1, 1);
  60535. }
  60536. }
  60537. else {
  60538. var index_2 = this._engine.postProcesses.indexOf(this);
  60539. if (index_2 !== -1) {
  60540. this._engine.postProcesses.splice(index_2, 1);
  60541. }
  60542. }
  60543. if (!camera) {
  60544. return;
  60545. }
  60546. camera.detachPostProcess(this);
  60547. var index = camera._postProcesses.indexOf(this);
  60548. if (index === 0 && camera._postProcesses.length > 0) {
  60549. var firstPostProcess = this._camera._getFirstPostProcess();
  60550. if (firstPostProcess) {
  60551. firstPostProcess.markTextureDirty();
  60552. }
  60553. }
  60554. this.onActivateObservable.clear();
  60555. this.onAfterRenderObservable.clear();
  60556. this.onApplyObservable.clear();
  60557. this.onBeforeRenderObservable.clear();
  60558. this.onSizeChangedObservable.clear();
  60559. };
  60560. return PostProcess;
  60561. }());
  60562. BABYLON.PostProcess = PostProcess;
  60563. })(BABYLON || (BABYLON = {}));
  60564. //# sourceMappingURL=babylon.postProcess.js.map
  60565. var BABYLON;
  60566. (function (BABYLON) {
  60567. var PassPostProcess = /** @class */ (function (_super) {
  60568. __extends(PassPostProcess, _super);
  60569. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  60570. if (camera === void 0) { camera = null; }
  60571. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60572. if (blockCompilation === void 0) { blockCompilation = false; }
  60573. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  60574. }
  60575. return PassPostProcess;
  60576. }(BABYLON.PostProcess));
  60577. BABYLON.PassPostProcess = PassPostProcess;
  60578. })(BABYLON || (BABYLON = {}));
  60579. //# sourceMappingURL=babylon.passPostProcess.js.map
  60580. var __assign = (this && this.__assign) || Object.assign || function(t) {
  60581. for (var s, i = 1, n = arguments.length; i < n; i++) {
  60582. s = arguments[i];
  60583. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  60584. t[p] = s[p];
  60585. }
  60586. return t;
  60587. };
  60588. var BABYLON;
  60589. (function (BABYLON) {
  60590. /**
  60591. * Default implementation of @see IShadowGenerator.
  60592. * This is the main object responsible of generating shadows in the framework.
  60593. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  60594. */
  60595. var ShadowGenerator = /** @class */ (function () {
  60596. /**
  60597. * Creates a ShadowGenerator object.
  60598. * A ShadowGenerator is the required tool to use the shadows.
  60599. * Each light casting shadows needs to use its own ShadowGenerator.
  60600. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  60601. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  60602. * @param light The light object generating the shadows.
  60603. * @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.
  60604. */
  60605. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  60606. this._bias = 0.00005;
  60607. this._normalBias = 0;
  60608. this._blurBoxOffset = 1;
  60609. this._blurScale = 2;
  60610. this._blurKernel = 1;
  60611. this._useKernelBlur = false;
  60612. this._filter = ShadowGenerator.FILTER_NONE;
  60613. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  60614. this._contactHardeningLightSizeUVRatio = 0.1;
  60615. this._darkness = 0;
  60616. this._transparencyShadow = false;
  60617. /**
  60618. * Controls the extent to which the shadows fade out at the edge of the frustum
  60619. * Used only by directionals and spots
  60620. */
  60621. this.frustumEdgeFalloff = 0;
  60622. /**
  60623. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  60624. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  60625. * It might on the other hand introduce peter panning.
  60626. */
  60627. this.forceBackFacesOnly = false;
  60628. this._lightDirection = BABYLON.Vector3.Zero();
  60629. this._viewMatrix = BABYLON.Matrix.Zero();
  60630. this._projectionMatrix = BABYLON.Matrix.Zero();
  60631. this._transformMatrix = BABYLON.Matrix.Zero();
  60632. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  60633. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  60634. this._currentFaceIndex = 0;
  60635. this._currentFaceIndexCache = 0;
  60636. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  60637. this._mapSize = mapSize;
  60638. this._light = light;
  60639. this._scene = light.getScene();
  60640. light._shadowGenerator = this;
  60641. // Texture type fallback from float to int if not supported.
  60642. var caps = this._scene.getEngine().getCaps();
  60643. if (!useFullFloatFirst) {
  60644. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  60645. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60646. }
  60647. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  60648. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60649. }
  60650. else {
  60651. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60652. }
  60653. }
  60654. else {
  60655. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  60656. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60657. }
  60658. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  60659. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60660. }
  60661. else {
  60662. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60663. }
  60664. }
  60665. this._initializeGenerator();
  60666. this._applyFilterValues();
  60667. }
  60668. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  60669. /**
  60670. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  60671. */
  60672. get: function () {
  60673. return this._bias;
  60674. },
  60675. /**
  60676. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  60677. */
  60678. set: function (bias) {
  60679. this._bias = bias;
  60680. },
  60681. enumerable: true,
  60682. configurable: true
  60683. });
  60684. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  60685. /**
  60686. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  60687. */
  60688. get: function () {
  60689. return this._normalBias;
  60690. },
  60691. /**
  60692. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  60693. */
  60694. set: function (normalBias) {
  60695. this._normalBias = normalBias;
  60696. },
  60697. enumerable: true,
  60698. configurable: true
  60699. });
  60700. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  60701. /**
  60702. * Gets the blur box offset: offset applied during the blur pass.
  60703. * Only usefull if useKernelBlur = false
  60704. */
  60705. get: function () {
  60706. return this._blurBoxOffset;
  60707. },
  60708. /**
  60709. * Sets the blur box offset: offset applied during the blur pass.
  60710. * Only usefull if useKernelBlur = false
  60711. */
  60712. set: function (value) {
  60713. if (this._blurBoxOffset === value) {
  60714. return;
  60715. }
  60716. this._blurBoxOffset = value;
  60717. this._disposeBlurPostProcesses();
  60718. },
  60719. enumerable: true,
  60720. configurable: true
  60721. });
  60722. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  60723. /**
  60724. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  60725. * 2 means half of the size.
  60726. */
  60727. get: function () {
  60728. return this._blurScale;
  60729. },
  60730. /**
  60731. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  60732. * 2 means half of the size.
  60733. */
  60734. set: function (value) {
  60735. if (this._blurScale === value) {
  60736. return;
  60737. }
  60738. this._blurScale = value;
  60739. this._disposeBlurPostProcesses();
  60740. },
  60741. enumerable: true,
  60742. configurable: true
  60743. });
  60744. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  60745. /**
  60746. * Gets the blur kernel: kernel size of the blur pass.
  60747. * Only usefull if useKernelBlur = true
  60748. */
  60749. get: function () {
  60750. return this._blurKernel;
  60751. },
  60752. /**
  60753. * Sets the blur kernel: kernel size of the blur pass.
  60754. * Only usefull if useKernelBlur = true
  60755. */
  60756. set: function (value) {
  60757. if (this._blurKernel === value) {
  60758. return;
  60759. }
  60760. this._blurKernel = value;
  60761. this._disposeBlurPostProcesses();
  60762. },
  60763. enumerable: true,
  60764. configurable: true
  60765. });
  60766. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  60767. /**
  60768. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  60769. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  60770. */
  60771. get: function () {
  60772. return this._useKernelBlur;
  60773. },
  60774. /**
  60775. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  60776. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  60777. */
  60778. set: function (value) {
  60779. if (this._useKernelBlur === value) {
  60780. return;
  60781. }
  60782. this._useKernelBlur = value;
  60783. this._disposeBlurPostProcesses();
  60784. },
  60785. enumerable: true,
  60786. configurable: true
  60787. });
  60788. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  60789. /**
  60790. * Gets the depth scale used in ESM mode.
  60791. */
  60792. get: function () {
  60793. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  60794. },
  60795. /**
  60796. * Sets the depth scale used in ESM mode.
  60797. * This can override the scale stored on the light.
  60798. */
  60799. set: function (value) {
  60800. this._depthScale = value;
  60801. },
  60802. enumerable: true,
  60803. configurable: true
  60804. });
  60805. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  60806. /**
  60807. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  60808. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  60809. */
  60810. get: function () {
  60811. return this._filter;
  60812. },
  60813. /**
  60814. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  60815. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  60816. */
  60817. set: function (value) {
  60818. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  60819. if (this._light.needCube()) {
  60820. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  60821. this.useExponentialShadowMap = true;
  60822. return;
  60823. }
  60824. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  60825. this.useCloseExponentialShadowMap = true;
  60826. return;
  60827. }
  60828. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  60829. this.usePoissonSampling = true;
  60830. return;
  60831. }
  60832. }
  60833. // Weblg1 fallback for PCF.
  60834. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  60835. if (this._scene.getEngine().webGLVersion === 1) {
  60836. this.usePoissonSampling = true;
  60837. return;
  60838. }
  60839. }
  60840. if (this._filter === value) {
  60841. return;
  60842. }
  60843. this._filter = value;
  60844. this._disposeBlurPostProcesses();
  60845. this._applyFilterValues();
  60846. this._light._markMeshesAsLightDirty();
  60847. },
  60848. enumerable: true,
  60849. configurable: true
  60850. });
  60851. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  60852. /**
  60853. * Gets if the current filter is set to Poisson Sampling.
  60854. */
  60855. get: function () {
  60856. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  60857. },
  60858. /**
  60859. * Sets the current filter to Poisson Sampling.
  60860. */
  60861. set: function (value) {
  60862. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  60863. return;
  60864. }
  60865. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  60866. },
  60867. enumerable: true,
  60868. configurable: true
  60869. });
  60870. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  60871. /**
  60872. * Gets if the current filter is set to VSM.
  60873. * DEPRECATED. Should use useExponentialShadowMap instead.
  60874. */
  60875. get: function () {
  60876. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  60877. return this.useExponentialShadowMap;
  60878. },
  60879. /**
  60880. * Sets the current filter is to VSM.
  60881. * DEPRECATED. Should use useExponentialShadowMap instead.
  60882. */
  60883. set: function (value) {
  60884. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  60885. this.useExponentialShadowMap = value;
  60886. },
  60887. enumerable: true,
  60888. configurable: true
  60889. });
  60890. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  60891. /**
  60892. * Gets if the current filter is set to blurred VSM.
  60893. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  60894. */
  60895. get: function () {
  60896. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  60897. return this.useBlurExponentialShadowMap;
  60898. },
  60899. /**
  60900. * Sets the current filter is to blurred VSM.
  60901. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  60902. */
  60903. set: function (value) {
  60904. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  60905. this.useBlurExponentialShadowMap = value;
  60906. },
  60907. enumerable: true,
  60908. configurable: true
  60909. });
  60910. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  60911. /**
  60912. * Gets if the current filter is set to ESM.
  60913. */
  60914. get: function () {
  60915. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  60916. },
  60917. /**
  60918. * Sets the current filter is to ESM.
  60919. */
  60920. set: function (value) {
  60921. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  60922. return;
  60923. }
  60924. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60925. },
  60926. enumerable: true,
  60927. configurable: true
  60928. });
  60929. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  60930. /**
  60931. * Gets if the current filter is set to filtered ESM.
  60932. */
  60933. get: function () {
  60934. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  60935. },
  60936. /**
  60937. * Gets if the current filter is set to filtered ESM.
  60938. */
  60939. set: function (value) {
  60940. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  60941. return;
  60942. }
  60943. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60944. },
  60945. enumerable: true,
  60946. configurable: true
  60947. });
  60948. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  60949. /**
  60950. * Gets if the current filter is set to "close ESM" (using the inverse of the
  60951. * exponential to prevent steep falloff artifacts).
  60952. */
  60953. get: function () {
  60954. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  60955. },
  60956. /**
  60957. * Sets the current filter to "close ESM" (using the inverse of the
  60958. * exponential to prevent steep falloff artifacts).
  60959. */
  60960. set: function (value) {
  60961. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  60962. return;
  60963. }
  60964. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60965. },
  60966. enumerable: true,
  60967. configurable: true
  60968. });
  60969. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  60970. /**
  60971. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  60972. * exponential to prevent steep falloff artifacts).
  60973. */
  60974. get: function () {
  60975. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  60976. },
  60977. /**
  60978. * Sets the current filter to filtered "close ESM" (using the inverse of the
  60979. * exponential to prevent steep falloff artifacts).
  60980. */
  60981. set: function (value) {
  60982. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  60983. return;
  60984. }
  60985. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60986. },
  60987. enumerable: true,
  60988. configurable: true
  60989. });
  60990. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  60991. /**
  60992. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  60993. */
  60994. get: function () {
  60995. return this.filter === ShadowGenerator.FILTER_PCF;
  60996. },
  60997. /**
  60998. * Sets the current filter to "PCF" (percentage closer filtering).
  60999. */
  61000. set: function (value) {
  61001. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  61002. return;
  61003. }
  61004. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  61005. },
  61006. enumerable: true,
  61007. configurable: true
  61008. });
  61009. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  61010. /**
  61011. * Gets the PCF or PCSS Quality.
  61012. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  61013. */
  61014. get: function () {
  61015. return this._filteringQuality;
  61016. },
  61017. /**
  61018. * Sets the PCF or PCSS Quality.
  61019. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  61020. */
  61021. set: function (filteringQuality) {
  61022. this._filteringQuality = filteringQuality;
  61023. },
  61024. enumerable: true,
  61025. configurable: true
  61026. });
  61027. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  61028. /**
  61029. * Gets if the current filter is set to "PCSS" (contact hardening).
  61030. */
  61031. get: function () {
  61032. return this.filter === ShadowGenerator.FILTER_PCSS;
  61033. },
  61034. /**
  61035. * Sets the current filter to "PCSS" (contact hardening).
  61036. */
  61037. set: function (value) {
  61038. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  61039. return;
  61040. }
  61041. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  61042. },
  61043. enumerable: true,
  61044. configurable: true
  61045. });
  61046. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  61047. /**
  61048. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  61049. * Using a ratio helps keeping shape stability independently of the map size.
  61050. *
  61051. * It does not account for the light projection as it was having too much
  61052. * instability during the light setup or during light position changes.
  61053. *
  61054. * Only valid if useContactHardeningShadow is true.
  61055. */
  61056. get: function () {
  61057. return this._contactHardeningLightSizeUVRatio;
  61058. },
  61059. /**
  61060. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  61061. * Using a ratio helps keeping shape stability independently of the map size.
  61062. *
  61063. * It does not account for the light projection as it was having too much
  61064. * instability during the light setup or during light position changes.
  61065. *
  61066. * Only valid if useContactHardeningShadow is true.
  61067. */
  61068. set: function (contactHardeningLightSizeUVRatio) {
  61069. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  61070. },
  61071. enumerable: true,
  61072. configurable: true
  61073. });
  61074. /**
  61075. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  61076. * 0 means strongest and 1 would means no shadow.
  61077. * @returns the darkness.
  61078. */
  61079. ShadowGenerator.prototype.getDarkness = function () {
  61080. return this._darkness;
  61081. };
  61082. /**
  61083. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  61084. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  61085. * @returns the shadow generator allowing fluent coding.
  61086. */
  61087. ShadowGenerator.prototype.setDarkness = function (darkness) {
  61088. if (darkness >= 1.0)
  61089. this._darkness = 1.0;
  61090. else if (darkness <= 0.0)
  61091. this._darkness = 0.0;
  61092. else
  61093. this._darkness = darkness;
  61094. return this;
  61095. };
  61096. /**
  61097. * Sets the ability to have transparent shadow (boolean).
  61098. * @param transparent True if transparent else False
  61099. * @returns the shadow generator allowing fluent coding
  61100. */
  61101. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  61102. this._transparencyShadow = transparent;
  61103. return this;
  61104. };
  61105. /**
  61106. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  61107. * @returns The render target texture if present otherwise, null
  61108. */
  61109. ShadowGenerator.prototype.getShadowMap = function () {
  61110. return this._shadowMap;
  61111. };
  61112. /**
  61113. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  61114. * @returns The render target texture if the shadow map is present otherwise, null
  61115. */
  61116. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  61117. if (this._shadowMap2) {
  61118. return this._shadowMap2;
  61119. }
  61120. return this._shadowMap;
  61121. };
  61122. /**
  61123. * Helper function to add a mesh and its descendants to the list of shadow casters.
  61124. * @param mesh Mesh to add
  61125. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  61126. * @returns the Shadow Generator itself
  61127. */
  61128. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  61129. if (includeDescendants === void 0) { includeDescendants = true; }
  61130. if (!this._shadowMap) {
  61131. return this;
  61132. }
  61133. if (!this._shadowMap.renderList) {
  61134. this._shadowMap.renderList = [];
  61135. }
  61136. this._shadowMap.renderList.push(mesh);
  61137. if (includeDescendants) {
  61138. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  61139. }
  61140. return this;
  61141. var _a;
  61142. };
  61143. /**
  61144. * Helper function to remove a mesh and its descendants from the list of shadow casters
  61145. * @param mesh Mesh to remove
  61146. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  61147. * @returns the Shadow Generator itself
  61148. */
  61149. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  61150. if (includeDescendants === void 0) { includeDescendants = true; }
  61151. if (!this._shadowMap || !this._shadowMap.renderList) {
  61152. return this;
  61153. }
  61154. var index = this._shadowMap.renderList.indexOf(mesh);
  61155. if (index !== -1) {
  61156. this._shadowMap.renderList.splice(index, 1);
  61157. }
  61158. if (includeDescendants) {
  61159. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  61160. var child = _a[_i];
  61161. this.removeShadowCaster(child);
  61162. }
  61163. }
  61164. return this;
  61165. };
  61166. /**
  61167. * Returns the associated light object.
  61168. * @returns the light generating the shadow
  61169. */
  61170. ShadowGenerator.prototype.getLight = function () {
  61171. return this._light;
  61172. };
  61173. ShadowGenerator.prototype._initializeGenerator = function () {
  61174. this._light._markMeshesAsLightDirty();
  61175. this._initializeShadowMap();
  61176. };
  61177. ShadowGenerator.prototype._initializeShadowMap = function () {
  61178. var _this = this;
  61179. // Render target
  61180. var engine = this._scene.getEngine();
  61181. if (engine.webGLVersion > 1) {
  61182. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  61183. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  61184. }
  61185. else {
  61186. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  61187. }
  61188. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61189. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61190. this._shadowMap.anisotropicFilteringLevel = 1;
  61191. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61192. this._shadowMap.renderParticles = false;
  61193. this._shadowMap.ignoreCameraViewport = true;
  61194. // Record Face Index before render.
  61195. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  61196. _this._currentFaceIndex = faceIndex;
  61197. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61198. engine.setColorWrite(false);
  61199. }
  61200. });
  61201. // Custom render function.
  61202. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  61203. // Blur if required afer render.
  61204. this._shadowMap.onAfterUnbindObservable.add(function () {
  61205. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61206. engine.setColorWrite(true);
  61207. }
  61208. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  61209. return;
  61210. }
  61211. var shadowMap = _this.getShadowMapForRendering();
  61212. if (shadowMap) {
  61213. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  61214. }
  61215. });
  61216. // Clear according to the chosen filter.
  61217. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  61218. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  61219. this._shadowMap.onClearObservable.add(function (engine) {
  61220. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61221. engine.clear(clearOne, false, true, false);
  61222. }
  61223. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  61224. engine.clear(clearZero, true, true, false);
  61225. }
  61226. else {
  61227. engine.clear(clearOne, true, true, false);
  61228. }
  61229. });
  61230. };
  61231. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  61232. var _this = this;
  61233. var engine = this._scene.getEngine();
  61234. var targetSize = this._mapSize / this.blurScale;
  61235. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  61236. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  61237. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61238. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61239. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61240. }
  61241. if (this.useKernelBlur) {
  61242. 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);
  61243. this._kernelBlurXPostprocess.width = targetSize;
  61244. this._kernelBlurXPostprocess.height = targetSize;
  61245. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  61246. effect.setTexture("textureSampler", _this._shadowMap);
  61247. });
  61248. 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);
  61249. this._kernelBlurXPostprocess.autoClear = false;
  61250. this._kernelBlurYPostprocess.autoClear = false;
  61251. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  61252. this._kernelBlurXPostprocess.packedFloat = true;
  61253. this._kernelBlurYPostprocess.packedFloat = true;
  61254. }
  61255. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  61256. }
  61257. else {
  61258. 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);
  61259. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  61260. effect.setFloat2("screenSize", targetSize, targetSize);
  61261. effect.setTexture("textureSampler", _this._shadowMap);
  61262. });
  61263. this._boxBlurPostprocess.autoClear = false;
  61264. this._blurPostProcesses = [this._boxBlurPostprocess];
  61265. }
  61266. };
  61267. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  61268. var index;
  61269. var engine = this._scene.getEngine();
  61270. if (depthOnlySubMeshes.length) {
  61271. engine.setColorWrite(false);
  61272. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  61273. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  61274. }
  61275. engine.setColorWrite(true);
  61276. }
  61277. for (index = 0; index < opaqueSubMeshes.length; index++) {
  61278. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  61279. }
  61280. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  61281. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  61282. }
  61283. if (this._transparencyShadow) {
  61284. for (index = 0; index < transparentSubMeshes.length; index++) {
  61285. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  61286. }
  61287. }
  61288. };
  61289. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  61290. var _this = this;
  61291. var mesh = subMesh.getRenderingMesh();
  61292. var scene = this._scene;
  61293. var engine = scene.getEngine();
  61294. var material = subMesh.getMaterial();
  61295. if (!material) {
  61296. return;
  61297. }
  61298. // Culling
  61299. engine.setState(material.backFaceCulling);
  61300. // Managing instances
  61301. var batch = mesh._getInstancesRenderList(subMesh._id);
  61302. if (batch.mustReturn) {
  61303. return;
  61304. }
  61305. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  61306. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  61307. engine.enableEffect(this._effect);
  61308. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  61309. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  61310. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  61311. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  61312. this._effect.setVector3("lightData", this._cachedDirection);
  61313. }
  61314. else {
  61315. this._effect.setVector3("lightData", this._cachedPosition);
  61316. }
  61317. if (scene.activeCamera) {
  61318. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  61319. }
  61320. // Alpha test
  61321. if (material && material.needAlphaTesting()) {
  61322. var alphaTexture = material.getAlphaTestTexture();
  61323. if (alphaTexture) {
  61324. this._effect.setTexture("diffuseSampler", alphaTexture);
  61325. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  61326. }
  61327. }
  61328. // Bones
  61329. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61330. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  61331. }
  61332. if (this.forceBackFacesOnly) {
  61333. engine.setState(true, 0, false, true);
  61334. }
  61335. // Draw
  61336. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  61337. if (this.forceBackFacesOnly) {
  61338. engine.setState(true, 0, false, false);
  61339. }
  61340. }
  61341. else {
  61342. // Need to reset refresh rate of the shadowMap
  61343. if (this._shadowMap) {
  61344. this._shadowMap.resetRefreshCounter();
  61345. }
  61346. }
  61347. };
  61348. ShadowGenerator.prototype._applyFilterValues = function () {
  61349. if (!this._shadowMap) {
  61350. return;
  61351. }
  61352. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  61353. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  61354. }
  61355. else {
  61356. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61357. }
  61358. };
  61359. /**
  61360. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  61361. * @param onCompiled Callback triggered at the and of the effects compilation
  61362. * @param options Sets of optional options forcing the compilation with different modes
  61363. */
  61364. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  61365. var _this = this;
  61366. var localOptions = __assign({ useInstances: false }, options);
  61367. var shadowMap = this.getShadowMap();
  61368. if (!shadowMap) {
  61369. if (onCompiled) {
  61370. onCompiled(this);
  61371. }
  61372. return;
  61373. }
  61374. var renderList = shadowMap.renderList;
  61375. if (!renderList) {
  61376. if (onCompiled) {
  61377. onCompiled(this);
  61378. }
  61379. return;
  61380. }
  61381. var subMeshes = new Array();
  61382. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  61383. var mesh = renderList_1[_i];
  61384. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  61385. }
  61386. if (subMeshes.length === 0) {
  61387. if (onCompiled) {
  61388. onCompiled(this);
  61389. }
  61390. return;
  61391. }
  61392. var currentIndex = 0;
  61393. var checkReady = function () {
  61394. if (!_this._scene || !_this._scene.getEngine()) {
  61395. return;
  61396. }
  61397. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  61398. currentIndex++;
  61399. if (currentIndex >= subMeshes.length) {
  61400. if (onCompiled) {
  61401. onCompiled(_this);
  61402. }
  61403. return;
  61404. }
  61405. }
  61406. setTimeout(checkReady, 16);
  61407. };
  61408. checkReady();
  61409. };
  61410. /**
  61411. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  61412. * @param options Sets of optional options forcing the compilation with different modes
  61413. * @returns A promise that resolves when the compilation completes
  61414. */
  61415. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  61416. var _this = this;
  61417. return new Promise(function (resolve) {
  61418. _this.forceCompilation(function () {
  61419. resolve();
  61420. }, options);
  61421. });
  61422. };
  61423. /**
  61424. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  61425. * @param subMesh The submesh we want to render in the shadow map
  61426. * @param useInstances Defines wether will draw in the map using instances
  61427. * @returns true if ready otherwise, false
  61428. */
  61429. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  61430. var defines = [];
  61431. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  61432. defines.push("#define FLOAT");
  61433. }
  61434. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  61435. defines.push("#define ESM");
  61436. }
  61437. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  61438. defines.push("#define DEPTHTEXTURE");
  61439. }
  61440. var attribs = [BABYLON.VertexBuffer.PositionKind];
  61441. var mesh = subMesh.getMesh();
  61442. var material = subMesh.getMaterial();
  61443. // Normal bias.
  61444. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  61445. attribs.push(BABYLON.VertexBuffer.NormalKind);
  61446. defines.push("#define NORMAL");
  61447. if (mesh.nonUniformScaling) {
  61448. defines.push("#define NONUNIFORMSCALING");
  61449. }
  61450. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  61451. defines.push("#define DIRECTIONINLIGHTDATA");
  61452. }
  61453. }
  61454. // Alpha test
  61455. if (material && material.needAlphaTesting()) {
  61456. var alphaTexture = material.getAlphaTestTexture();
  61457. if (alphaTexture) {
  61458. defines.push("#define ALPHATEST");
  61459. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61460. attribs.push(BABYLON.VertexBuffer.UVKind);
  61461. defines.push("#define UV1");
  61462. }
  61463. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  61464. if (alphaTexture.coordinatesIndex === 1) {
  61465. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61466. defines.push("#define UV2");
  61467. }
  61468. }
  61469. }
  61470. }
  61471. // Bones
  61472. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61473. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61474. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61475. if (mesh.numBoneInfluencers > 4) {
  61476. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61477. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61478. }
  61479. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61480. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  61481. }
  61482. else {
  61483. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61484. }
  61485. // Instances
  61486. if (useInstances) {
  61487. defines.push("#define INSTANCES");
  61488. attribs.push("world0");
  61489. attribs.push("world1");
  61490. attribs.push("world2");
  61491. attribs.push("world3");
  61492. }
  61493. // Get correct effect
  61494. var join = defines.join("\n");
  61495. if (this._cachedDefines !== join) {
  61496. this._cachedDefines = join;
  61497. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  61498. }
  61499. if (!this._effect.isReady()) {
  61500. return false;
  61501. }
  61502. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  61503. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  61504. this._initializeBlurRTTAndPostProcesses();
  61505. }
  61506. }
  61507. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  61508. return false;
  61509. }
  61510. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  61511. return false;
  61512. }
  61513. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  61514. return false;
  61515. }
  61516. return true;
  61517. };
  61518. /**
  61519. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  61520. * @param defines Defines of the material we want to update
  61521. * @param lightIndex Index of the light in the enabled light list of the material
  61522. */
  61523. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  61524. var scene = this._scene;
  61525. var light = this._light;
  61526. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  61527. return;
  61528. }
  61529. defines["SHADOW" + lightIndex] = true;
  61530. if (this.useContactHardeningShadow) {
  61531. defines["SHADOWPCSS" + lightIndex] = true;
  61532. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  61533. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  61534. }
  61535. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  61536. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  61537. }
  61538. // else default to high.
  61539. }
  61540. if (this.usePercentageCloserFiltering) {
  61541. defines["SHADOWPCF" + lightIndex] = true;
  61542. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  61543. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  61544. }
  61545. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  61546. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  61547. }
  61548. // else default to high.
  61549. }
  61550. else if (this.usePoissonSampling) {
  61551. defines["SHADOWPOISSON" + lightIndex] = true;
  61552. }
  61553. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  61554. defines["SHADOWESM" + lightIndex] = true;
  61555. }
  61556. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  61557. defines["SHADOWCLOSEESM" + lightIndex] = true;
  61558. }
  61559. if (light.needCube()) {
  61560. defines["SHADOWCUBE" + lightIndex] = true;
  61561. }
  61562. };
  61563. /**
  61564. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  61565. * defined in the generator but impacting the effect).
  61566. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  61567. * @param effect The effect we are binfing the information for
  61568. */
  61569. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  61570. var light = this._light;
  61571. var scene = this._scene;
  61572. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  61573. return;
  61574. }
  61575. var camera = scene.activeCamera;
  61576. if (!camera) {
  61577. return;
  61578. }
  61579. var shadowMap = this.getShadowMap();
  61580. if (!shadowMap) {
  61581. return;
  61582. }
  61583. if (!light.needCube()) {
  61584. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  61585. }
  61586. // Only PCF uses depth stencil texture.
  61587. if (this._filter === ShadowGenerator.FILTER_PCF) {
  61588. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  61589. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  61590. }
  61591. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  61592. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  61593. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  61594. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  61595. }
  61596. else {
  61597. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  61598. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  61599. }
  61600. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  61601. };
  61602. /**
  61603. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  61604. * (eq to shadow prjection matrix * light transform matrix)
  61605. * @returns The transform matrix used to create the shadow map
  61606. */
  61607. ShadowGenerator.prototype.getTransformMatrix = function () {
  61608. var scene = this._scene;
  61609. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  61610. return this._transformMatrix;
  61611. }
  61612. this._currentRenderID = scene.getRenderId();
  61613. this._currentFaceIndexCache = this._currentFaceIndex;
  61614. var lightPosition = this._light.position;
  61615. if (this._light.computeTransformedInformation()) {
  61616. lightPosition = this._light.transformedPosition;
  61617. }
  61618. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  61619. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  61620. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  61621. }
  61622. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  61623. this._cachedPosition.copyFrom(lightPosition);
  61624. this._cachedDirection.copyFrom(this._lightDirection);
  61625. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  61626. var shadowMap = this.getShadowMap();
  61627. if (shadowMap) {
  61628. var renderList = shadowMap.renderList;
  61629. if (renderList) {
  61630. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  61631. }
  61632. }
  61633. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  61634. }
  61635. return this._transformMatrix;
  61636. };
  61637. /**
  61638. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  61639. * Cube and 2D textures for instance.
  61640. */
  61641. ShadowGenerator.prototype.recreateShadowMap = function () {
  61642. var shadowMap = this._shadowMap;
  61643. if (!shadowMap) {
  61644. return;
  61645. }
  61646. // Track render list.
  61647. var renderList = shadowMap.renderList;
  61648. // Clean up existing data.
  61649. this._disposeRTTandPostProcesses();
  61650. // Reinitializes.
  61651. this._initializeGenerator();
  61652. // Reaffect the filter to ensure a correct fallback if necessary.
  61653. this.filter = this.filter;
  61654. // Reaffect the filter.
  61655. this._applyFilterValues();
  61656. // Reaffect Render List.
  61657. this._shadowMap.renderList = renderList;
  61658. };
  61659. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  61660. if (this._shadowMap2) {
  61661. this._shadowMap2.dispose();
  61662. this._shadowMap2 = null;
  61663. }
  61664. if (this._boxBlurPostprocess) {
  61665. this._boxBlurPostprocess.dispose();
  61666. this._boxBlurPostprocess = null;
  61667. }
  61668. if (this._kernelBlurXPostprocess) {
  61669. this._kernelBlurXPostprocess.dispose();
  61670. this._kernelBlurXPostprocess = null;
  61671. }
  61672. if (this._kernelBlurYPostprocess) {
  61673. this._kernelBlurYPostprocess.dispose();
  61674. this._kernelBlurYPostprocess = null;
  61675. }
  61676. this._blurPostProcesses = [];
  61677. };
  61678. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  61679. if (this._shadowMap) {
  61680. this._shadowMap.dispose();
  61681. this._shadowMap = null;
  61682. }
  61683. this._disposeBlurPostProcesses();
  61684. };
  61685. /**
  61686. * Disposes the ShadowGenerator.
  61687. * Returns nothing.
  61688. */
  61689. ShadowGenerator.prototype.dispose = function () {
  61690. this._disposeRTTandPostProcesses();
  61691. if (this._light) {
  61692. this._light._shadowGenerator = null;
  61693. this._light._markMeshesAsLightDirty();
  61694. }
  61695. };
  61696. /**
  61697. * Serializes the shadow generator setup to a json object.
  61698. * @returns The serialized JSON object
  61699. */
  61700. ShadowGenerator.prototype.serialize = function () {
  61701. var serializationObject = {};
  61702. var shadowMap = this.getShadowMap();
  61703. if (!shadowMap) {
  61704. return serializationObject;
  61705. }
  61706. serializationObject.lightId = this._light.id;
  61707. serializationObject.mapSize = shadowMap.getRenderSize();
  61708. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  61709. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  61710. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  61711. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  61712. serializationObject.usePoissonSampling = this.usePoissonSampling;
  61713. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  61714. serializationObject.depthScale = this.depthScale;
  61715. serializationObject.darkness = this.getDarkness();
  61716. serializationObject.blurBoxOffset = this.blurBoxOffset;
  61717. serializationObject.blurKernel = this.blurKernel;
  61718. serializationObject.blurScale = this.blurScale;
  61719. serializationObject.useKernelBlur = this.useKernelBlur;
  61720. serializationObject.transparencyShadow = this._transparencyShadow;
  61721. serializationObject.bias = this.bias;
  61722. serializationObject.normalBias = this.normalBias;
  61723. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  61724. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  61725. serializationObject.filteringQuality = this.filteringQuality;
  61726. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  61727. serializationObject.renderList = [];
  61728. if (shadowMap.renderList) {
  61729. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  61730. var mesh = shadowMap.renderList[meshIndex];
  61731. serializationObject.renderList.push(mesh.id);
  61732. }
  61733. }
  61734. return serializationObject;
  61735. };
  61736. /**
  61737. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  61738. * @param parsedShadowGenerator The JSON object to parse
  61739. * @param scene The scene to create the shadow map for
  61740. * @returns The parsed shadow generator
  61741. */
  61742. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  61743. //casting to point light, as light is missing the position attr and typescript complains.
  61744. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  61745. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  61746. var shadowMap = shadowGenerator.getShadowMap();
  61747. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  61748. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  61749. meshes.forEach(function (mesh) {
  61750. if (!shadowMap) {
  61751. return;
  61752. }
  61753. if (!shadowMap.renderList) {
  61754. shadowMap.renderList = [];
  61755. }
  61756. shadowMap.renderList.push(mesh);
  61757. });
  61758. }
  61759. if (parsedShadowGenerator.usePoissonSampling) {
  61760. shadowGenerator.usePoissonSampling = true;
  61761. }
  61762. else if (parsedShadowGenerator.useExponentialShadowMap) {
  61763. shadowGenerator.useExponentialShadowMap = true;
  61764. }
  61765. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  61766. shadowGenerator.useBlurExponentialShadowMap = true;
  61767. }
  61768. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  61769. shadowGenerator.useCloseExponentialShadowMap = true;
  61770. }
  61771. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  61772. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  61773. }
  61774. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  61775. shadowGenerator.usePercentageCloserFiltering = true;
  61776. }
  61777. else if (parsedShadowGenerator.useContactHardeningShadow) {
  61778. shadowGenerator.useContactHardeningShadow = true;
  61779. }
  61780. if (parsedShadowGenerator.filteringQuality) {
  61781. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  61782. }
  61783. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  61784. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  61785. }
  61786. else if (parsedShadowGenerator.useVarianceShadowMap) {
  61787. shadowGenerator.useExponentialShadowMap = true;
  61788. }
  61789. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  61790. shadowGenerator.useBlurExponentialShadowMap = true;
  61791. }
  61792. if (parsedShadowGenerator.depthScale) {
  61793. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  61794. }
  61795. if (parsedShadowGenerator.blurScale) {
  61796. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  61797. }
  61798. if (parsedShadowGenerator.blurBoxOffset) {
  61799. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  61800. }
  61801. if (parsedShadowGenerator.useKernelBlur) {
  61802. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  61803. }
  61804. if (parsedShadowGenerator.blurKernel) {
  61805. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  61806. }
  61807. if (parsedShadowGenerator.bias !== undefined) {
  61808. shadowGenerator.bias = parsedShadowGenerator.bias;
  61809. }
  61810. if (parsedShadowGenerator.normalBias !== undefined) {
  61811. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  61812. }
  61813. if (parsedShadowGenerator.darkness) {
  61814. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  61815. }
  61816. if (parsedShadowGenerator.transparencyShadow) {
  61817. shadowGenerator.setTransparencyShadow(true);
  61818. }
  61819. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  61820. return shadowGenerator;
  61821. };
  61822. /**
  61823. * Shadow generator mode None: no filtering applied.
  61824. */
  61825. ShadowGenerator.FILTER_NONE = 0;
  61826. /**
  61827. * Shadow generator mode ESM: Exponential Shadow Mapping.
  61828. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  61829. */
  61830. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  61831. /**
  61832. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  61833. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  61834. */
  61835. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  61836. /**
  61837. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  61838. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  61839. */
  61840. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  61841. /**
  61842. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  61843. * edge artifacts on steep falloff.
  61844. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  61845. */
  61846. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  61847. /**
  61848. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  61849. * edge artifacts on steep falloff.
  61850. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  61851. */
  61852. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  61853. /**
  61854. * Shadow generator mode PCF: Percentage Closer Filtering
  61855. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  61856. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  61857. */
  61858. ShadowGenerator.FILTER_PCF = 6;
  61859. /**
  61860. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  61861. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  61862. * Contact Hardening
  61863. */
  61864. ShadowGenerator.FILTER_PCSS = 7;
  61865. /**
  61866. * Reserved for PCF and PCSS
  61867. * Highest Quality.
  61868. *
  61869. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  61870. *
  61871. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  61872. */
  61873. ShadowGenerator.QUALITY_HIGH = 0;
  61874. /**
  61875. * Reserved for PCF and PCSS
  61876. * Good tradeoff for quality/perf cross devices
  61877. *
  61878. * Execute PCF on a 3*3 kernel.
  61879. *
  61880. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  61881. */
  61882. ShadowGenerator.QUALITY_MEDIUM = 1;
  61883. /**
  61884. * Reserved for PCF and PCSS
  61885. * The lowest quality but the fastest.
  61886. *
  61887. * Execute PCF on a 1*1 kernel.
  61888. *
  61889. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  61890. */
  61891. ShadowGenerator.QUALITY_LOW = 2;
  61892. return ShadowGenerator;
  61893. }());
  61894. BABYLON.ShadowGenerator = ShadowGenerator;
  61895. })(BABYLON || (BABYLON = {}));
  61896. //# sourceMappingURL=babylon.shadowGenerator.js.map
  61897. var BABYLON;
  61898. (function (BABYLON) {
  61899. var DefaultLoadingScreen = /** @class */ (function () {
  61900. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  61901. if (_loadingText === void 0) { _loadingText = ""; }
  61902. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  61903. var _this = this;
  61904. this._renderingCanvas = _renderingCanvas;
  61905. this._loadingText = _loadingText;
  61906. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  61907. // Resize
  61908. this._resizeLoadingUI = function () {
  61909. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  61910. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  61911. if (!_this._loadingDiv) {
  61912. return;
  61913. }
  61914. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  61915. _this._loadingDiv.style.left = canvasRect.left + "px";
  61916. _this._loadingDiv.style.top = canvasRect.top + "px";
  61917. _this._loadingDiv.style.width = canvasRect.width + "px";
  61918. _this._loadingDiv.style.height = canvasRect.height + "px";
  61919. };
  61920. }
  61921. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  61922. if (this._loadingDiv) {
  61923. // Do not add a loading screen if there is already one
  61924. return;
  61925. }
  61926. this._loadingDiv = document.createElement("div");
  61927. this._loadingDiv.id = "babylonjsLoadingDiv";
  61928. this._loadingDiv.style.opacity = "0";
  61929. this._loadingDiv.style.transition = "opacity 1.5s ease";
  61930. this._loadingDiv.style.pointerEvents = "none";
  61931. // Loading text
  61932. this._loadingTextDiv = document.createElement("div");
  61933. this._loadingTextDiv.style.position = "absolute";
  61934. this._loadingTextDiv.style.left = "0";
  61935. this._loadingTextDiv.style.top = "50%";
  61936. this._loadingTextDiv.style.marginTop = "80px";
  61937. this._loadingTextDiv.style.width = "100%";
  61938. this._loadingTextDiv.style.height = "20px";
  61939. this._loadingTextDiv.style.fontFamily = "Arial";
  61940. this._loadingTextDiv.style.fontSize = "14px";
  61941. this._loadingTextDiv.style.color = "white";
  61942. this._loadingTextDiv.style.textAlign = "center";
  61943. this._loadingTextDiv.innerHTML = "Loading";
  61944. this._loadingDiv.appendChild(this._loadingTextDiv);
  61945. //set the predefined text
  61946. this._loadingTextDiv.innerHTML = this._loadingText;
  61947. // Generating keyframes
  61948. var style = document.createElement('style');
  61949. style.type = 'text/css';
  61950. 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 }";
  61951. style.innerHTML = keyFrames;
  61952. document.getElementsByTagName('head')[0].appendChild(style);
  61953. // Loading img
  61954. var imgBack = new Image();
  61955. 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";
  61956. imgBack.style.position = "absolute";
  61957. imgBack.style.left = "50%";
  61958. imgBack.style.top = "50%";
  61959. imgBack.style.marginLeft = "-60px";
  61960. imgBack.style.marginTop = "-60px";
  61961. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  61962. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  61963. imgBack.style.transformOrigin = "50% 50%";
  61964. imgBack.style.webkitTransformOrigin = "50% 50%";
  61965. this._loadingDiv.appendChild(imgBack);
  61966. this._resizeLoadingUI();
  61967. window.addEventListener("resize", this._resizeLoadingUI);
  61968. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  61969. document.body.appendChild(this._loadingDiv);
  61970. this._loadingDiv.style.opacity = "1";
  61971. };
  61972. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  61973. var _this = this;
  61974. if (!this._loadingDiv) {
  61975. return;
  61976. }
  61977. var onTransitionEnd = function () {
  61978. if (!_this._loadingDiv) {
  61979. return;
  61980. }
  61981. document.body.removeChild(_this._loadingDiv);
  61982. window.removeEventListener("resize", _this._resizeLoadingUI);
  61983. _this._loadingDiv = null;
  61984. };
  61985. this._loadingDiv.style.opacity = "0";
  61986. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  61987. };
  61988. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  61989. set: function (text) {
  61990. this._loadingText = text;
  61991. if (this._loadingTextDiv) {
  61992. this._loadingTextDiv.innerHTML = this._loadingText;
  61993. }
  61994. },
  61995. enumerable: true,
  61996. configurable: true
  61997. });
  61998. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  61999. get: function () {
  62000. return this._loadingDivBackgroundColor;
  62001. },
  62002. set: function (color) {
  62003. this._loadingDivBackgroundColor = color;
  62004. if (!this._loadingDiv) {
  62005. return;
  62006. }
  62007. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  62008. },
  62009. enumerable: true,
  62010. configurable: true
  62011. });
  62012. return DefaultLoadingScreen;
  62013. }());
  62014. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  62015. })(BABYLON || (BABYLON = {}));
  62016. //# sourceMappingURL=babylon.loadingScreen.js.map
  62017. var BABYLON;
  62018. (function (BABYLON) {
  62019. var SceneLoaderProgressEvent = /** @class */ (function () {
  62020. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  62021. this.lengthComputable = lengthComputable;
  62022. this.loaded = loaded;
  62023. this.total = total;
  62024. }
  62025. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  62026. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  62027. };
  62028. return SceneLoaderProgressEvent;
  62029. }());
  62030. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  62031. var SceneLoader = /** @class */ (function () {
  62032. function SceneLoader() {
  62033. }
  62034. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  62035. get: function () {
  62036. return 0;
  62037. },
  62038. enumerable: true,
  62039. configurable: true
  62040. });
  62041. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  62042. get: function () {
  62043. return 1;
  62044. },
  62045. enumerable: true,
  62046. configurable: true
  62047. });
  62048. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  62049. get: function () {
  62050. return 2;
  62051. },
  62052. enumerable: true,
  62053. configurable: true
  62054. });
  62055. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  62056. get: function () {
  62057. return 3;
  62058. },
  62059. enumerable: true,
  62060. configurable: true
  62061. });
  62062. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  62063. get: function () {
  62064. return SceneLoader._ForceFullSceneLoadingForIncremental;
  62065. },
  62066. set: function (value) {
  62067. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  62068. },
  62069. enumerable: true,
  62070. configurable: true
  62071. });
  62072. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  62073. get: function () {
  62074. return SceneLoader._ShowLoadingScreen;
  62075. },
  62076. set: function (value) {
  62077. SceneLoader._ShowLoadingScreen = value;
  62078. },
  62079. enumerable: true,
  62080. configurable: true
  62081. });
  62082. Object.defineProperty(SceneLoader, "loggingLevel", {
  62083. get: function () {
  62084. return SceneLoader._loggingLevel;
  62085. },
  62086. set: function (value) {
  62087. SceneLoader._loggingLevel = value;
  62088. },
  62089. enumerable: true,
  62090. configurable: true
  62091. });
  62092. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  62093. get: function () {
  62094. return SceneLoader._CleanBoneMatrixWeights;
  62095. },
  62096. set: function (value) {
  62097. SceneLoader._CleanBoneMatrixWeights = value;
  62098. },
  62099. enumerable: true,
  62100. configurable: true
  62101. });
  62102. SceneLoader._getDefaultPlugin = function () {
  62103. return SceneLoader._registeredPlugins[".babylon"];
  62104. };
  62105. SceneLoader._getPluginForExtension = function (extension) {
  62106. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  62107. if (registeredPlugin) {
  62108. return registeredPlugin;
  62109. }
  62110. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  62111. return SceneLoader._getDefaultPlugin();
  62112. };
  62113. SceneLoader._getPluginForDirectLoad = function (data) {
  62114. for (var extension in SceneLoader._registeredPlugins) {
  62115. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  62116. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  62117. return SceneLoader._registeredPlugins[extension];
  62118. }
  62119. }
  62120. return SceneLoader._getDefaultPlugin();
  62121. };
  62122. SceneLoader._getPluginForFilename = function (sceneFilename) {
  62123. if (sceneFilename.name) {
  62124. sceneFilename = sceneFilename.name;
  62125. }
  62126. var queryStringPosition = sceneFilename.indexOf("?");
  62127. if (queryStringPosition !== -1) {
  62128. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  62129. }
  62130. var dotPosition = sceneFilename.lastIndexOf(".");
  62131. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  62132. return SceneLoader._getPluginForExtension(extension);
  62133. };
  62134. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  62135. SceneLoader._getDirectLoad = function (sceneFilename) {
  62136. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  62137. return sceneFilename.substr(5);
  62138. }
  62139. return null;
  62140. };
  62141. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  62142. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  62143. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  62144. var plugin;
  62145. if (registeredPlugin.plugin.createPlugin) {
  62146. plugin = registeredPlugin.plugin.createPlugin();
  62147. }
  62148. else {
  62149. plugin = registeredPlugin.plugin;
  62150. }
  62151. var useArrayBuffer = registeredPlugin.isBinary;
  62152. var database;
  62153. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  62154. var dataCallback = function (data, responseURL) {
  62155. if (scene.isDisposed) {
  62156. onError("Scene has been disposed");
  62157. return;
  62158. }
  62159. scene.database = database;
  62160. onSuccess(plugin, data, responseURL);
  62161. };
  62162. var request = null;
  62163. var pluginDisposed = false;
  62164. var onDisposeObservable = plugin.onDisposeObservable;
  62165. if (onDisposeObservable) {
  62166. onDisposeObservable.add(function () {
  62167. pluginDisposed = true;
  62168. if (request) {
  62169. request.abort();
  62170. request = null;
  62171. }
  62172. onDispose();
  62173. });
  62174. }
  62175. var manifestChecked = function () {
  62176. if (pluginDisposed) {
  62177. return;
  62178. }
  62179. var url = rootUrl + sceneFilename;
  62180. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  62181. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  62182. } : undefined, database, useArrayBuffer, function (request, exception) {
  62183. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  62184. });
  62185. };
  62186. if (directLoad) {
  62187. dataCallback(directLoad);
  62188. return plugin;
  62189. }
  62190. if (rootUrl.indexOf("file:") === -1) {
  62191. if (scene.getEngine().enableOfflineSupport) {
  62192. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  62193. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  62194. }
  62195. else {
  62196. manifestChecked();
  62197. }
  62198. }
  62199. else {
  62200. var fileOrString = sceneFilename;
  62201. if (fileOrString.name) {
  62202. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  62203. }
  62204. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  62205. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  62206. }
  62207. else {
  62208. onError("Unable to find file named " + sceneFilename);
  62209. }
  62210. }
  62211. return plugin;
  62212. };
  62213. // Public functions
  62214. SceneLoader.GetPluginForExtension = function (extension) {
  62215. return SceneLoader._getPluginForExtension(extension).plugin;
  62216. };
  62217. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  62218. return !!SceneLoader._registeredPlugins[extension];
  62219. };
  62220. SceneLoader.RegisterPlugin = function (plugin) {
  62221. if (typeof plugin.extensions === "string") {
  62222. var extension = plugin.extensions;
  62223. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  62224. plugin: plugin,
  62225. isBinary: false
  62226. };
  62227. }
  62228. else {
  62229. var extensions = plugin.extensions;
  62230. Object.keys(extensions).forEach(function (extension) {
  62231. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  62232. plugin: plugin,
  62233. isBinary: extensions[extension].isBinary
  62234. };
  62235. });
  62236. }
  62237. };
  62238. /**
  62239. * Import meshes into a scene
  62240. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  62241. * @param rootUrl a string that defines the root url for scene and resources
  62242. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62243. * @param scene the instance of BABYLON.Scene to append to
  62244. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  62245. * @param onProgress a callback with a progress event for each file being loaded
  62246. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62247. * @param pluginExtension the extension used to determine the plugin
  62248. * @returns The loaded plugin
  62249. */
  62250. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62251. if (onSuccess === void 0) { onSuccess = null; }
  62252. if (onProgress === void 0) { onProgress = null; }
  62253. if (onError === void 0) { onError = null; }
  62254. if (pluginExtension === void 0) { pluginExtension = null; }
  62255. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62256. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62257. return null;
  62258. }
  62259. var loadingToken = {};
  62260. scene._addPendingData(loadingToken);
  62261. var disposeHandler = function () {
  62262. scene._removePendingData(loadingToken);
  62263. };
  62264. var errorHandler = function (message, exception) {
  62265. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  62266. if (onError) {
  62267. onError(scene, errorMessage, exception);
  62268. }
  62269. else {
  62270. BABYLON.Tools.Error(errorMessage);
  62271. // should the exception be thrown?
  62272. }
  62273. disposeHandler();
  62274. };
  62275. var progressHandler = onProgress ? function (event) {
  62276. try {
  62277. onProgress(event);
  62278. }
  62279. catch (e) {
  62280. errorHandler("Error in onProgress callback", e);
  62281. }
  62282. } : undefined;
  62283. var successHandler = function (meshes, particleSystems, skeletons) {
  62284. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  62285. if (onSuccess) {
  62286. try {
  62287. onSuccess(meshes, particleSystems, skeletons);
  62288. }
  62289. catch (e) {
  62290. errorHandler("Error in onSuccess callback", e);
  62291. }
  62292. }
  62293. scene._removePendingData(loadingToken);
  62294. };
  62295. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62296. if (plugin.rewriteRootURL) {
  62297. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  62298. }
  62299. if (sceneFilename === "") {
  62300. if (sceneFilename === "") {
  62301. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  62302. }
  62303. }
  62304. if (plugin.importMesh) {
  62305. var syncedPlugin = plugin;
  62306. var meshes = new Array();
  62307. var particleSystems = new Array();
  62308. var skeletons = new Array();
  62309. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  62310. return;
  62311. }
  62312. scene.loadingPluginName = plugin.name;
  62313. successHandler(meshes, particleSystems, skeletons);
  62314. }
  62315. else {
  62316. var asyncedPlugin = plugin;
  62317. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  62318. scene.loadingPluginName = plugin.name;
  62319. successHandler(result.meshes, result.particleSystems, result.skeletons);
  62320. }).catch(function (error) {
  62321. errorHandler(error.message, error);
  62322. });
  62323. }
  62324. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62325. };
  62326. /**
  62327. * Import meshes into a scene
  62328. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  62329. * @param rootUrl a string that defines the root url for scene and resources
  62330. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62331. * @param scene the instance of BABYLON.Scene to append to
  62332. * @param onProgress a callback with a progress event for each file being loaded
  62333. * @param pluginExtension the extension used to determine the plugin
  62334. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  62335. */
  62336. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62337. if (onProgress === void 0) { onProgress = null; }
  62338. if (pluginExtension === void 0) { pluginExtension = null; }
  62339. return new Promise(function (resolve, reject) {
  62340. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  62341. resolve({
  62342. meshes: meshes,
  62343. particleSystems: particleSystems,
  62344. skeletons: skeletons
  62345. });
  62346. }, onProgress, function (scene, message, exception) {
  62347. reject(exception || new Error(message));
  62348. });
  62349. });
  62350. };
  62351. /**
  62352. * Load a scene
  62353. * @param rootUrl a string that defines the root url for scene and resources
  62354. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62355. * @param engine is the instance of BABYLON.Engine to use to create the scene
  62356. * @param onSuccess a callback with the scene when import succeeds
  62357. * @param onProgress a callback with a progress event for each file being loaded
  62358. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62359. * @param pluginExtension the extension used to determine the plugin
  62360. * @returns The loaded plugin
  62361. */
  62362. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  62363. if (onSuccess === void 0) { onSuccess = null; }
  62364. if (onProgress === void 0) { onProgress = null; }
  62365. if (onError === void 0) { onError = null; }
  62366. if (pluginExtension === void 0) { pluginExtension = null; }
  62367. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  62368. };
  62369. /**
  62370. * Load a scene
  62371. * @param rootUrl a string that defines the root url for scene and resources
  62372. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62373. * @param engine is the instance of BABYLON.Engine to use to create the scene
  62374. * @param onProgress a callback with a progress event for each file being loaded
  62375. * @param pluginExtension the extension used to determine the plugin
  62376. * @returns The loaded scene
  62377. */
  62378. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  62379. if (onProgress === void 0) { onProgress = null; }
  62380. if (pluginExtension === void 0) { pluginExtension = null; }
  62381. return new Promise(function (resolve, reject) {
  62382. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  62383. resolve(scene);
  62384. }, onProgress, function (scene, message, exception) {
  62385. reject(exception || new Error(message));
  62386. }, pluginExtension);
  62387. });
  62388. };
  62389. /**
  62390. * Append a scene
  62391. * @param rootUrl a string that defines the root url for scene and resources
  62392. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62393. * @param scene is the instance of BABYLON.Scene to append to
  62394. * @param onSuccess a callback with the scene when import succeeds
  62395. * @param onProgress a callback with a progress event for each file being loaded
  62396. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62397. * @param pluginExtension the extension used to determine the plugin
  62398. * @returns The loaded plugin
  62399. */
  62400. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62401. if (onSuccess === void 0) { onSuccess = null; }
  62402. if (onProgress === void 0) { onProgress = null; }
  62403. if (onError === void 0) { onError = null; }
  62404. if (pluginExtension === void 0) { pluginExtension = null; }
  62405. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62406. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62407. return null;
  62408. }
  62409. if (SceneLoader.ShowLoadingScreen) {
  62410. scene.getEngine().displayLoadingUI();
  62411. }
  62412. var loadingToken = {};
  62413. scene._addPendingData(loadingToken);
  62414. var disposeHandler = function () {
  62415. scene._removePendingData(loadingToken);
  62416. scene.getEngine().hideLoadingUI();
  62417. };
  62418. var errorHandler = function (message, exception) {
  62419. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  62420. if (onError) {
  62421. onError(scene, errorMessage, exception);
  62422. }
  62423. else {
  62424. BABYLON.Tools.Error(errorMessage);
  62425. // should the exception be thrown?
  62426. }
  62427. disposeHandler();
  62428. };
  62429. var progressHandler = onProgress ? function (event) {
  62430. try {
  62431. onProgress(event);
  62432. }
  62433. catch (e) {
  62434. errorHandler("Error in onProgress callback", e);
  62435. }
  62436. } : undefined;
  62437. var successHandler = function () {
  62438. if (onSuccess) {
  62439. try {
  62440. onSuccess(scene);
  62441. }
  62442. catch (e) {
  62443. errorHandler("Error in onSuccess callback", e);
  62444. }
  62445. }
  62446. scene._removePendingData(loadingToken);
  62447. };
  62448. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62449. if (sceneFilename === "") {
  62450. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  62451. }
  62452. if (plugin.load) {
  62453. var syncedPlugin = plugin;
  62454. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  62455. return;
  62456. }
  62457. scene.loadingPluginName = plugin.name;
  62458. successHandler();
  62459. }
  62460. else {
  62461. var asyncedPlugin = plugin;
  62462. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  62463. scene.loadingPluginName = plugin.name;
  62464. successHandler();
  62465. }).catch(function (error) {
  62466. errorHandler(error.message, error);
  62467. });
  62468. }
  62469. if (SceneLoader.ShowLoadingScreen) {
  62470. scene.executeWhenReady(function () {
  62471. scene.getEngine().hideLoadingUI();
  62472. });
  62473. }
  62474. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62475. };
  62476. /**
  62477. * Append a scene
  62478. * @param rootUrl a string that defines the root url for scene and resources
  62479. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62480. * @param scene is the instance of BABYLON.Scene to append to
  62481. * @param onProgress a callback with a progress event for each file being loaded
  62482. * @param pluginExtension the extension used to determine the plugin
  62483. * @returns The given scene
  62484. */
  62485. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62486. if (onProgress === void 0) { onProgress = null; }
  62487. if (pluginExtension === void 0) { pluginExtension = null; }
  62488. return new Promise(function (resolve, reject) {
  62489. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  62490. resolve(scene);
  62491. }, onProgress, function (scene, message, exception) {
  62492. reject(exception || new Error(message));
  62493. }, pluginExtension);
  62494. });
  62495. };
  62496. /**
  62497. * Load a scene into an asset container
  62498. * @param rootUrl a string that defines the root url for scene and resources
  62499. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62500. * @param scene is the instance of BABYLON.Scene to append to
  62501. * @param onSuccess a callback with the scene when import succeeds
  62502. * @param onProgress a callback with a progress event for each file being loaded
  62503. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62504. * @param pluginExtension the extension used to determine the plugin
  62505. * @returns The loaded plugin
  62506. */
  62507. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62508. if (onSuccess === void 0) { onSuccess = null; }
  62509. if (onProgress === void 0) { onProgress = null; }
  62510. if (onError === void 0) { onError = null; }
  62511. if (pluginExtension === void 0) { pluginExtension = null; }
  62512. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62513. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62514. return null;
  62515. }
  62516. var loadingToken = {};
  62517. scene._addPendingData(loadingToken);
  62518. var disposeHandler = function () {
  62519. scene._removePendingData(loadingToken);
  62520. };
  62521. var errorHandler = function (message, exception) {
  62522. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  62523. if (onError) {
  62524. onError(scene, errorMessage, exception);
  62525. }
  62526. else {
  62527. BABYLON.Tools.Error(errorMessage);
  62528. // should the exception be thrown?
  62529. }
  62530. disposeHandler();
  62531. };
  62532. var progressHandler = onProgress ? function (event) {
  62533. try {
  62534. onProgress(event);
  62535. }
  62536. catch (e) {
  62537. errorHandler("Error in onProgress callback", e);
  62538. }
  62539. } : undefined;
  62540. var successHandler = function (assets) {
  62541. if (onSuccess) {
  62542. try {
  62543. onSuccess(assets);
  62544. }
  62545. catch (e) {
  62546. errorHandler("Error in onSuccess callback", e);
  62547. }
  62548. }
  62549. scene._removePendingData(loadingToken);
  62550. };
  62551. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62552. if (plugin.loadAssetContainer) {
  62553. var syncedPlugin = plugin;
  62554. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  62555. if (!assetContainer) {
  62556. return;
  62557. }
  62558. scene.loadingPluginName = plugin.name;
  62559. successHandler(assetContainer);
  62560. }
  62561. else if (plugin.loadAssetContainerAsync) {
  62562. var asyncedPlugin = plugin;
  62563. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  62564. scene.loadingPluginName = plugin.name;
  62565. successHandler(assetContainer);
  62566. }).catch(function (error) {
  62567. errorHandler(error.message, error);
  62568. });
  62569. }
  62570. else {
  62571. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  62572. }
  62573. if (SceneLoader.ShowLoadingScreen) {
  62574. scene.executeWhenReady(function () {
  62575. scene.getEngine().hideLoadingUI();
  62576. });
  62577. }
  62578. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62579. };
  62580. /**
  62581. * Load a scene into an asset container
  62582. * @param rootUrl a string that defines the root url for scene and resources
  62583. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62584. * @param scene is the instance of BABYLON.Scene to append to
  62585. * @param onProgress a callback with a progress event for each file being loaded
  62586. * @param pluginExtension the extension used to determine the plugin
  62587. * @returns The loaded asset container
  62588. */
  62589. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62590. if (onProgress === void 0) { onProgress = null; }
  62591. if (pluginExtension === void 0) { pluginExtension = null; }
  62592. return new Promise(function (resolve, reject) {
  62593. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  62594. resolve(assetContainer);
  62595. }, onProgress, function (scene, message, exception) {
  62596. reject(exception || new Error(message));
  62597. }, pluginExtension);
  62598. });
  62599. };
  62600. // Flags
  62601. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  62602. SceneLoader._ShowLoadingScreen = true;
  62603. SceneLoader._CleanBoneMatrixWeights = false;
  62604. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  62605. // Members
  62606. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  62607. SceneLoader._registeredPlugins = {};
  62608. return SceneLoader;
  62609. }());
  62610. BABYLON.SceneLoader = SceneLoader;
  62611. ;
  62612. })(BABYLON || (BABYLON = {}));
  62613. //# sourceMappingURL=babylon.sceneLoader.js.map
  62614. var BABYLON;
  62615. (function (BABYLON) {
  62616. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  62617. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  62618. var parsedMaterial = parsedData.materials[index];
  62619. if (parsedMaterial.id === id) {
  62620. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  62621. }
  62622. }
  62623. return null;
  62624. };
  62625. var isDescendantOf = function (mesh, names, hierarchyIds) {
  62626. for (var i in names) {
  62627. if (mesh.name === names[i]) {
  62628. hierarchyIds.push(mesh.id);
  62629. return true;
  62630. }
  62631. }
  62632. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  62633. hierarchyIds.push(mesh.id);
  62634. return true;
  62635. }
  62636. return false;
  62637. };
  62638. var logOperation = function (operation, producer) {
  62639. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  62640. };
  62641. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  62642. if (addToScene === void 0) { addToScene = false; }
  62643. var container = new BABYLON.AssetContainer(scene);
  62644. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62645. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62646. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62647. // and avoid problems with multiple concurrent .babylon loads.
  62648. var log = "importScene has failed JSON parse";
  62649. try {
  62650. var parsedData = JSON.parse(data);
  62651. log = "";
  62652. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  62653. var index;
  62654. var cache;
  62655. // Lights
  62656. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  62657. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  62658. var parsedLight = parsedData.lights[index];
  62659. var light = BABYLON.Light.Parse(parsedLight, scene);
  62660. if (light) {
  62661. container.lights.push(light);
  62662. log += (index === 0 ? "\n\tLights:" : "");
  62663. log += "\n\t\t" + light.toString(fullDetails);
  62664. }
  62665. }
  62666. }
  62667. // Animations
  62668. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  62669. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  62670. var parsedAnimation = parsedData.animations[index];
  62671. var animation = BABYLON.Animation.Parse(parsedAnimation);
  62672. scene.animations.push(animation);
  62673. container.animations.push(animation);
  62674. log += (index === 0 ? "\n\tAnimations:" : "");
  62675. log += "\n\t\t" + animation.toString(fullDetails);
  62676. }
  62677. }
  62678. // Materials
  62679. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  62680. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  62681. var parsedMaterial = parsedData.materials[index];
  62682. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  62683. container.materials.push(mat);
  62684. log += (index === 0 ? "\n\tMaterials:" : "");
  62685. log += "\n\t\t" + mat.toString(fullDetails);
  62686. }
  62687. }
  62688. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  62689. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  62690. var parsedMultiMaterial = parsedData.multiMaterials[index];
  62691. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  62692. container.multiMaterials.push(mmat);
  62693. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  62694. log += "\n\t\t" + mmat.toString(fullDetails);
  62695. }
  62696. }
  62697. // Morph targets
  62698. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  62699. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  62700. var managerData = _a[_i];
  62701. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  62702. }
  62703. }
  62704. // Skeletons
  62705. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  62706. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  62707. var parsedSkeleton = parsedData.skeletons[index];
  62708. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  62709. container.skeletons.push(skeleton);
  62710. log += (index === 0 ? "\n\tSkeletons:" : "");
  62711. log += "\n\t\t" + skeleton.toString(fullDetails);
  62712. }
  62713. }
  62714. // Geometries
  62715. var geometries = parsedData.geometries;
  62716. if (geometries !== undefined && geometries !== null) {
  62717. var addedGeometry = new Array();
  62718. // Boxes
  62719. var boxes = geometries.boxes;
  62720. if (boxes !== undefined && boxes !== null) {
  62721. for (index = 0, cache = boxes.length; index < cache; index++) {
  62722. var parsedBox = boxes[index];
  62723. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  62724. }
  62725. }
  62726. // Spheres
  62727. var spheres = geometries.spheres;
  62728. if (spheres !== undefined && spheres !== null) {
  62729. for (index = 0, cache = spheres.length; index < cache; index++) {
  62730. var parsedSphere = spheres[index];
  62731. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  62732. }
  62733. }
  62734. // Cylinders
  62735. var cylinders = geometries.cylinders;
  62736. if (cylinders !== undefined && cylinders !== null) {
  62737. for (index = 0, cache = cylinders.length; index < cache; index++) {
  62738. var parsedCylinder = cylinders[index];
  62739. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  62740. }
  62741. }
  62742. // Toruses
  62743. var toruses = geometries.toruses;
  62744. if (toruses !== undefined && toruses !== null) {
  62745. for (index = 0, cache = toruses.length; index < cache; index++) {
  62746. var parsedTorus = toruses[index];
  62747. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  62748. }
  62749. }
  62750. // Grounds
  62751. var grounds = geometries.grounds;
  62752. if (grounds !== undefined && grounds !== null) {
  62753. for (index = 0, cache = grounds.length; index < cache; index++) {
  62754. var parsedGround = grounds[index];
  62755. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  62756. }
  62757. }
  62758. // Planes
  62759. var planes = geometries.planes;
  62760. if (planes !== undefined && planes !== null) {
  62761. for (index = 0, cache = planes.length; index < cache; index++) {
  62762. var parsedPlane = planes[index];
  62763. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  62764. }
  62765. }
  62766. // TorusKnots
  62767. var torusKnots = geometries.torusKnots;
  62768. if (torusKnots !== undefined && torusKnots !== null) {
  62769. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  62770. var parsedTorusKnot = torusKnots[index];
  62771. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  62772. }
  62773. }
  62774. // VertexData
  62775. var vertexData = geometries.vertexData;
  62776. if (vertexData !== undefined && vertexData !== null) {
  62777. for (index = 0, cache = vertexData.length; index < cache; index++) {
  62778. var parsedVertexData = vertexData[index];
  62779. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  62780. }
  62781. }
  62782. addedGeometry.forEach(function (g) {
  62783. if (g) {
  62784. container.geometries.push(g);
  62785. }
  62786. });
  62787. }
  62788. // Transform nodes
  62789. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  62790. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  62791. var parsedTransformNode = parsedData.transformNodes[index];
  62792. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  62793. container.transformNodes.push(node);
  62794. }
  62795. }
  62796. // Meshes
  62797. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  62798. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  62799. var parsedMesh = parsedData.meshes[index];
  62800. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  62801. container.meshes.push(mesh);
  62802. log += (index === 0 ? "\n\tMeshes:" : "");
  62803. log += "\n\t\t" + mesh.toString(fullDetails);
  62804. }
  62805. }
  62806. // Cameras
  62807. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  62808. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  62809. var parsedCamera = parsedData.cameras[index];
  62810. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  62811. container.cameras.push(camera);
  62812. log += (index === 0 ? "\n\tCameras:" : "");
  62813. log += "\n\t\t" + camera.toString(fullDetails);
  62814. }
  62815. }
  62816. // Browsing all the graph to connect the dots
  62817. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  62818. var camera = scene.cameras[index];
  62819. if (camera._waitingParentId) {
  62820. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  62821. camera._waitingParentId = null;
  62822. }
  62823. }
  62824. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  62825. var light_1 = scene.lights[index];
  62826. if (light_1 && light_1._waitingParentId) {
  62827. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  62828. light_1._waitingParentId = null;
  62829. }
  62830. }
  62831. // Sounds
  62832. // TODO: add sound
  62833. var loadedSounds = [];
  62834. var loadedSound;
  62835. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  62836. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  62837. var parsedSound = parsedData.sounds[index];
  62838. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62839. if (!parsedSound.url)
  62840. parsedSound.url = parsedSound.name;
  62841. if (!loadedSounds[parsedSound.url]) {
  62842. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  62843. loadedSounds[parsedSound.url] = loadedSound;
  62844. container.sounds.push(loadedSound);
  62845. }
  62846. else {
  62847. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  62848. }
  62849. }
  62850. else {
  62851. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  62852. }
  62853. }
  62854. }
  62855. loadedSounds = [];
  62856. // Connect parents & children and parse actions
  62857. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  62858. var transformNode = scene.transformNodes[index];
  62859. if (transformNode._waitingParentId) {
  62860. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  62861. transformNode._waitingParentId = null;
  62862. }
  62863. }
  62864. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62865. var mesh = scene.meshes[index];
  62866. if (mesh._waitingParentId) {
  62867. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  62868. mesh._waitingParentId = null;
  62869. }
  62870. if (mesh._waitingActions) {
  62871. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  62872. mesh._waitingActions = null;
  62873. }
  62874. }
  62875. // freeze world matrix application
  62876. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62877. var currentMesh = scene.meshes[index];
  62878. if (currentMesh._waitingFreezeWorldMatrix) {
  62879. currentMesh.freezeWorldMatrix();
  62880. currentMesh._waitingFreezeWorldMatrix = null;
  62881. }
  62882. else {
  62883. currentMesh.computeWorldMatrix(true);
  62884. }
  62885. }
  62886. // Particles Systems
  62887. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  62888. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  62889. var parsedParticleSystem = parsedData.particleSystems[index];
  62890. if (parsedParticleSystem.activeParticleCount) {
  62891. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62892. container.particleSystems.push(ps);
  62893. }
  62894. else {
  62895. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62896. container.particleSystems.push(ps);
  62897. }
  62898. }
  62899. }
  62900. // Lens flares
  62901. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  62902. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  62903. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  62904. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  62905. container.lensFlareSystems.push(lf);
  62906. }
  62907. }
  62908. // Shadows
  62909. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  62910. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  62911. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  62912. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  62913. container.shadowGenerators.push(sg);
  62914. }
  62915. }
  62916. // Lights exclusions / inclusions
  62917. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  62918. var light_2 = scene.lights[index];
  62919. // Excluded check
  62920. if (light_2._excludedMeshesIds.length > 0) {
  62921. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  62922. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  62923. if (excludedMesh) {
  62924. light_2.excludedMeshes.push(excludedMesh);
  62925. }
  62926. }
  62927. light_2._excludedMeshesIds = [];
  62928. }
  62929. // Included check
  62930. if (light_2._includedOnlyMeshesIds.length > 0) {
  62931. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  62932. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  62933. if (includedOnlyMesh) {
  62934. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  62935. }
  62936. }
  62937. light_2._includedOnlyMeshesIds = [];
  62938. }
  62939. }
  62940. // Actions (scene)
  62941. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  62942. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  62943. }
  62944. if (!addToScene) {
  62945. container.removeAllFromScene();
  62946. }
  62947. }
  62948. catch (err) {
  62949. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  62950. if (onError) {
  62951. onError(msg, err);
  62952. }
  62953. else {
  62954. BABYLON.Tools.Log(msg);
  62955. throw err;
  62956. }
  62957. }
  62958. finally {
  62959. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62960. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62961. }
  62962. }
  62963. return container;
  62964. };
  62965. BABYLON.SceneLoader.RegisterPlugin({
  62966. name: "babylon.js",
  62967. extensions: ".babylon",
  62968. canDirectLoad: function (data) {
  62969. if (data.indexOf("babylon") !== -1) {
  62970. return true;
  62971. }
  62972. return false;
  62973. },
  62974. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  62975. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62976. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62977. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62978. // and avoid problems with multiple concurrent .babylon loads.
  62979. var log = "importMesh has failed JSON parse";
  62980. try {
  62981. var parsedData = JSON.parse(data);
  62982. log = "";
  62983. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  62984. if (!meshesNames) {
  62985. meshesNames = null;
  62986. }
  62987. else if (!Array.isArray(meshesNames)) {
  62988. meshesNames = [meshesNames];
  62989. }
  62990. var hierarchyIds = new Array();
  62991. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  62992. var loadedSkeletonsIds = [];
  62993. var loadedMaterialsIds = [];
  62994. var index;
  62995. var cache;
  62996. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  62997. var parsedMesh = parsedData.meshes[index];
  62998. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  62999. if (meshesNames !== null) {
  63000. // Remove found mesh name from list.
  63001. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  63002. }
  63003. //Geometry?
  63004. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  63005. //does the file contain geometries?
  63006. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  63007. //find the correct geometry and add it to the scene
  63008. var found = false;
  63009. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  63010. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  63011. return;
  63012. }
  63013. else {
  63014. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  63015. if (parsedGeometryData.id === parsedMesh.geometryId) {
  63016. switch (geometryType) {
  63017. case "boxes":
  63018. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  63019. break;
  63020. case "spheres":
  63021. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  63022. break;
  63023. case "cylinders":
  63024. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  63025. break;
  63026. case "toruses":
  63027. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  63028. break;
  63029. case "grounds":
  63030. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  63031. break;
  63032. case "planes":
  63033. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  63034. break;
  63035. case "torusKnots":
  63036. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  63037. break;
  63038. case "vertexData":
  63039. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  63040. break;
  63041. }
  63042. found = true;
  63043. }
  63044. });
  63045. }
  63046. });
  63047. if (found === false) {
  63048. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  63049. }
  63050. }
  63051. }
  63052. // Material ?
  63053. if (parsedMesh.materialId) {
  63054. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  63055. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  63056. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  63057. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  63058. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  63059. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  63060. var subMatId = parsedMultiMaterial.materials[matIndex];
  63061. loadedMaterialsIds.push(subMatId);
  63062. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  63063. if (mat) {
  63064. log += "\n\tMaterial " + mat.toString(fullDetails);
  63065. }
  63066. }
  63067. loadedMaterialsIds.push(parsedMultiMaterial.id);
  63068. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  63069. if (mmat) {
  63070. materialFound = true;
  63071. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  63072. }
  63073. break;
  63074. }
  63075. }
  63076. }
  63077. if (materialFound === false) {
  63078. loadedMaterialsIds.push(parsedMesh.materialId);
  63079. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  63080. if (!mat) {
  63081. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  63082. }
  63083. else {
  63084. log += "\n\tMaterial " + mat.toString(fullDetails);
  63085. }
  63086. }
  63087. }
  63088. // Skeleton ?
  63089. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  63090. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  63091. if (skeletonAlreadyLoaded === false) {
  63092. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  63093. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  63094. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  63095. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  63096. skeletons.push(skeleton);
  63097. loadedSkeletonsIds.push(parsedSkeleton.id);
  63098. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  63099. }
  63100. }
  63101. }
  63102. }
  63103. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  63104. meshes.push(mesh);
  63105. log += "\n\tMesh " + mesh.toString(fullDetails);
  63106. }
  63107. }
  63108. // Connecting parents
  63109. var currentMesh;
  63110. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63111. currentMesh = scene.meshes[index];
  63112. if (currentMesh._waitingParentId) {
  63113. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  63114. currentMesh._waitingParentId = null;
  63115. }
  63116. }
  63117. // freeze and compute world matrix application
  63118. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63119. currentMesh = scene.meshes[index];
  63120. if (currentMesh._waitingFreezeWorldMatrix) {
  63121. currentMesh.freezeWorldMatrix();
  63122. currentMesh._waitingFreezeWorldMatrix = null;
  63123. }
  63124. else {
  63125. currentMesh.computeWorldMatrix(true);
  63126. }
  63127. }
  63128. }
  63129. // Particles
  63130. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  63131. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  63132. var parsedParticleSystem = parsedData.particleSystems[index];
  63133. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  63134. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  63135. }
  63136. }
  63137. }
  63138. return true;
  63139. }
  63140. catch (err) {
  63141. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  63142. if (onError) {
  63143. onError(msg, err);
  63144. }
  63145. else {
  63146. BABYLON.Tools.Log(msg);
  63147. throw err;
  63148. }
  63149. }
  63150. finally {
  63151. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63152. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63153. }
  63154. }
  63155. return false;
  63156. },
  63157. load: function (scene, data, rootUrl, onError) {
  63158. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63159. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63160. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63161. // and avoid problems with multiple concurrent .babylon loads.
  63162. var log = "importScene has failed JSON parse";
  63163. try {
  63164. var parsedData = JSON.parse(data);
  63165. log = "";
  63166. // Scene
  63167. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  63168. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  63169. }
  63170. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  63171. scene.autoClear = parsedData.autoClear;
  63172. }
  63173. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  63174. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  63175. }
  63176. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  63177. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  63178. }
  63179. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  63180. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  63181. }
  63182. // Fog
  63183. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  63184. scene.fogMode = parsedData.fogMode;
  63185. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  63186. scene.fogStart = parsedData.fogStart;
  63187. scene.fogEnd = parsedData.fogEnd;
  63188. scene.fogDensity = parsedData.fogDensity;
  63189. log += "\tFog mode for scene: ";
  63190. switch (scene.fogMode) {
  63191. // getters not compiling, so using hardcoded
  63192. case 1:
  63193. log += "exp\n";
  63194. break;
  63195. case 2:
  63196. log += "exp2\n";
  63197. break;
  63198. case 3:
  63199. log += "linear\n";
  63200. break;
  63201. }
  63202. }
  63203. //Physics
  63204. if (parsedData.physicsEnabled) {
  63205. var physicsPlugin;
  63206. if (parsedData.physicsEngine === "cannon") {
  63207. physicsPlugin = new BABYLON.CannonJSPlugin();
  63208. }
  63209. else if (parsedData.physicsEngine === "oimo") {
  63210. physicsPlugin = new BABYLON.OimoJSPlugin();
  63211. }
  63212. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  63213. //else - default engine, which is currently oimo
  63214. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  63215. scene.enablePhysics(physicsGravity, physicsPlugin);
  63216. }
  63217. // Metadata
  63218. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  63219. scene.metadata = parsedData.metadata;
  63220. }
  63221. //collisions, if defined. otherwise, default is true
  63222. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  63223. scene.collisionsEnabled = parsedData.collisionsEnabled;
  63224. }
  63225. scene.workerCollisions = !!parsedData.workerCollisions;
  63226. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  63227. if (!container) {
  63228. return false;
  63229. }
  63230. if (parsedData.autoAnimate) {
  63231. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  63232. }
  63233. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  63234. scene.setActiveCameraByID(parsedData.activeCameraID);
  63235. }
  63236. // Environment texture
  63237. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  63238. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  63239. if (parsedData.createDefaultSkybox === true) {
  63240. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  63241. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  63242. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  63243. }
  63244. }
  63245. // Finish
  63246. return true;
  63247. }
  63248. catch (err) {
  63249. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  63250. if (onError) {
  63251. onError(msg, err);
  63252. }
  63253. else {
  63254. BABYLON.Tools.Log(msg);
  63255. throw err;
  63256. }
  63257. }
  63258. finally {
  63259. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63260. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63261. }
  63262. }
  63263. return false;
  63264. },
  63265. loadAssetContainer: function (scene, data, rootUrl, onError) {
  63266. var container = loadAssetContainer(scene, data, rootUrl, onError);
  63267. return container;
  63268. }
  63269. });
  63270. })(BABYLON || (BABYLON = {}));
  63271. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  63272. var BABYLON;
  63273. (function (BABYLON) {
  63274. var FilesInput = /** @class */ (function () {
  63275. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  63276. this.onProcessFileCallback = function () { return true; };
  63277. this._engine = engine;
  63278. this._currentScene = scene;
  63279. this._sceneLoadedCallback = sceneLoadedCallback;
  63280. this._progressCallback = progressCallback;
  63281. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  63282. this._textureLoadingCallback = textureLoadingCallback;
  63283. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  63284. this._onReloadCallback = onReloadCallback;
  63285. this._errorCallback = errorCallback;
  63286. }
  63287. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  63288. var _this = this;
  63289. if (elementToMonitor) {
  63290. this._elementToMonitor = elementToMonitor;
  63291. this._dragEnterHandler = function (e) { _this.drag(e); };
  63292. this._dragOverHandler = function (e) { _this.drag(e); };
  63293. this._dropHandler = function (e) { _this.drop(e); };
  63294. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  63295. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  63296. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  63297. }
  63298. };
  63299. FilesInput.prototype.dispose = function () {
  63300. if (!this._elementToMonitor) {
  63301. return;
  63302. }
  63303. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  63304. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  63305. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  63306. };
  63307. FilesInput.prototype.renderFunction = function () {
  63308. if (this._additionalRenderLoopLogicCallback) {
  63309. this._additionalRenderLoopLogicCallback();
  63310. }
  63311. if (this._currentScene) {
  63312. if (this._textureLoadingCallback) {
  63313. var remaining = this._currentScene.getWaitingItemsCount();
  63314. if (remaining > 0) {
  63315. this._textureLoadingCallback(remaining);
  63316. }
  63317. }
  63318. this._currentScene.render();
  63319. }
  63320. };
  63321. FilesInput.prototype.drag = function (e) {
  63322. e.stopPropagation();
  63323. e.preventDefault();
  63324. };
  63325. FilesInput.prototype.drop = function (eventDrop) {
  63326. eventDrop.stopPropagation();
  63327. eventDrop.preventDefault();
  63328. this.loadFiles(eventDrop);
  63329. };
  63330. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  63331. var _this = this;
  63332. var reader = folder.createReader();
  63333. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  63334. reader.readEntries(function (entries) {
  63335. remaining.count += entries.length;
  63336. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  63337. var entry = entries_1[_i];
  63338. if (entry.isFile) {
  63339. entry.file(function (file) {
  63340. file.correctName = relativePath + file.name;
  63341. files.push(file);
  63342. if (--remaining.count === 0) {
  63343. callback();
  63344. }
  63345. });
  63346. }
  63347. else if (entry.isDirectory) {
  63348. _this._traverseFolder(entry, files, remaining, callback);
  63349. }
  63350. }
  63351. if (--remaining.count) {
  63352. callback();
  63353. }
  63354. });
  63355. };
  63356. FilesInput.prototype._processFiles = function (files) {
  63357. for (var i = 0; i < files.length; i++) {
  63358. var name = files[i].correctName.toLowerCase();
  63359. var extension = name.split('.').pop();
  63360. if (!this.onProcessFileCallback(files[i], name, extension)) {
  63361. continue;
  63362. }
  63363. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  63364. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  63365. this._sceneFileToLoad = files[i];
  63366. }
  63367. else {
  63368. FilesInput.FilesToLoad[name] = files[i];
  63369. }
  63370. }
  63371. };
  63372. FilesInput.prototype.loadFiles = function (event) {
  63373. var _this = this;
  63374. if (this._startingProcessingFilesCallback)
  63375. this._startingProcessingFilesCallback();
  63376. // Handling data transfer via drag'n'drop
  63377. if (event && event.dataTransfer && event.dataTransfer.files) {
  63378. this._filesToLoad = event.dataTransfer.files;
  63379. }
  63380. // Handling files from input files
  63381. if (event && event.target && event.target.files) {
  63382. this._filesToLoad = event.target.files;
  63383. }
  63384. if (this._filesToLoad && this._filesToLoad.length > 0) {
  63385. var files_1 = new Array();
  63386. var folders = [];
  63387. var items = event.dataTransfer ? event.dataTransfer.items : null;
  63388. for (var i = 0; i < this._filesToLoad.length; i++) {
  63389. var fileToLoad = this._filesToLoad[i];
  63390. var name_1 = fileToLoad.name.toLowerCase();
  63391. var entry = void 0;
  63392. fileToLoad.correctName = name_1;
  63393. if (items) {
  63394. var item = items[i];
  63395. if (item.getAsEntry) {
  63396. entry = item.getAsEntry();
  63397. }
  63398. else if (item.webkitGetAsEntry) {
  63399. entry = item.webkitGetAsEntry();
  63400. }
  63401. }
  63402. if (!entry) {
  63403. files_1.push(fileToLoad);
  63404. }
  63405. else {
  63406. if (entry.isDirectory) {
  63407. folders.push(entry);
  63408. }
  63409. else {
  63410. files_1.push(fileToLoad);
  63411. }
  63412. }
  63413. }
  63414. if (folders.length === 0) {
  63415. this._processFiles(files_1);
  63416. this._processReload();
  63417. }
  63418. else {
  63419. var remaining = { count: folders.length };
  63420. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  63421. var folder = folders_1[_i];
  63422. this._traverseFolder(folder, files_1, remaining, function () {
  63423. _this._processFiles(files_1);
  63424. if (remaining.count === 0) {
  63425. _this._processReload();
  63426. }
  63427. });
  63428. }
  63429. }
  63430. }
  63431. };
  63432. FilesInput.prototype._processReload = function () {
  63433. if (this._onReloadCallback) {
  63434. this._onReloadCallback(this._sceneFileToLoad);
  63435. }
  63436. else {
  63437. this.reload();
  63438. }
  63439. };
  63440. FilesInput.prototype.reload = function () {
  63441. var _this = this;
  63442. // If a scene file has been provided
  63443. if (this._sceneFileToLoad) {
  63444. if (this._currentScene) {
  63445. if (BABYLON.Tools.errorsCount > 0) {
  63446. BABYLON.Tools.ClearLogCache();
  63447. }
  63448. this._engine.stopRenderLoop();
  63449. this._currentScene.dispose();
  63450. }
  63451. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  63452. if (_this._progressCallback) {
  63453. _this._progressCallback(progress);
  63454. }
  63455. }).then(function (scene) {
  63456. _this._currentScene = scene;
  63457. if (_this._sceneLoadedCallback) {
  63458. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  63459. }
  63460. // Wait for textures and shaders to be ready
  63461. _this._currentScene.executeWhenReady(function () {
  63462. _this._engine.runRenderLoop(function () {
  63463. _this.renderFunction();
  63464. });
  63465. });
  63466. }).catch(function (error) {
  63467. if (_this._errorCallback) {
  63468. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  63469. }
  63470. });
  63471. }
  63472. else {
  63473. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  63474. }
  63475. };
  63476. FilesInput.FilesToLoad = {};
  63477. return FilesInput;
  63478. }());
  63479. BABYLON.FilesInput = FilesInput;
  63480. })(BABYLON || (BABYLON = {}));
  63481. //# sourceMappingURL=babylon.filesInput.js.map
  63482. var BABYLON;
  63483. (function (BABYLON) {
  63484. /**
  63485. * This class implement a typical dictionary using a string as key and the generic type T as value.
  63486. * The underlying implementation relies on an associative array to ensure the best performances.
  63487. * The value can be anything including 'null' but except 'undefined'
  63488. */
  63489. var StringDictionary = /** @class */ (function () {
  63490. function StringDictionary() {
  63491. this._count = 0;
  63492. this._data = {};
  63493. }
  63494. /**
  63495. * This will clear this dictionary and copy the content from the 'source' one.
  63496. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  63497. * @param source the dictionary to take the content from and copy to this dictionary
  63498. */
  63499. StringDictionary.prototype.copyFrom = function (source) {
  63500. var _this = this;
  63501. this.clear();
  63502. source.forEach(function (t, v) { return _this.add(t, v); });
  63503. };
  63504. /**
  63505. * Get a value based from its key
  63506. * @param key the given key to get the matching value from
  63507. * @return the value if found, otherwise undefined is returned
  63508. */
  63509. StringDictionary.prototype.get = function (key) {
  63510. var val = this._data[key];
  63511. if (val !== undefined) {
  63512. return val;
  63513. }
  63514. return undefined;
  63515. };
  63516. /**
  63517. * Get a value from its key or add it if it doesn't exist.
  63518. * This method will ensure you that a given key/data will be present in the dictionary.
  63519. * @param key the given key to get the matching value from
  63520. * @param factory the factory that will create the value if the key is not present in the dictionary.
  63521. * The factory will only be invoked if there's no data for the given key.
  63522. * @return the value corresponding to the key.
  63523. */
  63524. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  63525. var val = this.get(key);
  63526. if (val !== undefined) {
  63527. return val;
  63528. }
  63529. val = factory(key);
  63530. if (val) {
  63531. this.add(key, val);
  63532. }
  63533. return val;
  63534. };
  63535. /**
  63536. * Get a value from its key if present in the dictionary otherwise add it
  63537. * @param key the key to get the value from
  63538. * @param val if there's no such key/value pair in the dictionary add it with this value
  63539. * @return the value corresponding to the key
  63540. */
  63541. StringDictionary.prototype.getOrAdd = function (key, val) {
  63542. var curVal = this.get(key);
  63543. if (curVal !== undefined) {
  63544. return curVal;
  63545. }
  63546. this.add(key, val);
  63547. return val;
  63548. };
  63549. /**
  63550. * Check if there's a given key in the dictionary
  63551. * @param key the key to check for
  63552. * @return true if the key is present, false otherwise
  63553. */
  63554. StringDictionary.prototype.contains = function (key) {
  63555. return this._data[key] !== undefined;
  63556. };
  63557. /**
  63558. * Add a new key and its corresponding value
  63559. * @param key the key to add
  63560. * @param value the value corresponding to the key
  63561. * @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
  63562. */
  63563. StringDictionary.prototype.add = function (key, value) {
  63564. if (this._data[key] !== undefined) {
  63565. return false;
  63566. }
  63567. this._data[key] = value;
  63568. ++this._count;
  63569. return true;
  63570. };
  63571. StringDictionary.prototype.set = function (key, value) {
  63572. if (this._data[key] === undefined) {
  63573. return false;
  63574. }
  63575. this._data[key] = value;
  63576. return true;
  63577. };
  63578. /**
  63579. * Get the element of the given key and remove it from the dictionary
  63580. * @param key
  63581. */
  63582. StringDictionary.prototype.getAndRemove = function (key) {
  63583. var val = this.get(key);
  63584. if (val !== undefined) {
  63585. delete this._data[key];
  63586. --this._count;
  63587. return val;
  63588. }
  63589. return null;
  63590. };
  63591. /**
  63592. * Remove a key/value from the dictionary.
  63593. * @param key the key to remove
  63594. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  63595. */
  63596. StringDictionary.prototype.remove = function (key) {
  63597. if (this.contains(key)) {
  63598. delete this._data[key];
  63599. --this._count;
  63600. return true;
  63601. }
  63602. return false;
  63603. };
  63604. /**
  63605. * Clear the whole content of the dictionary
  63606. */
  63607. StringDictionary.prototype.clear = function () {
  63608. this._data = {};
  63609. this._count = 0;
  63610. };
  63611. Object.defineProperty(StringDictionary.prototype, "count", {
  63612. get: function () {
  63613. return this._count;
  63614. },
  63615. enumerable: true,
  63616. configurable: true
  63617. });
  63618. /**
  63619. * Execute a callback on each key/val of the dictionary.
  63620. * Note that you can remove any element in this dictionary in the callback implementation
  63621. * @param callback the callback to execute on a given key/value pair
  63622. */
  63623. StringDictionary.prototype.forEach = function (callback) {
  63624. for (var cur in this._data) {
  63625. var val = this._data[cur];
  63626. callback(cur, val);
  63627. }
  63628. };
  63629. /**
  63630. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  63631. * If the callback returns null or undefined the method will iterate to the next key/value pair
  63632. * Note that you can remove any element in this dictionary in the callback implementation
  63633. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  63634. */
  63635. StringDictionary.prototype.first = function (callback) {
  63636. for (var cur in this._data) {
  63637. var val = this._data[cur];
  63638. var res = callback(cur, val);
  63639. if (res) {
  63640. return res;
  63641. }
  63642. }
  63643. return null;
  63644. };
  63645. return StringDictionary;
  63646. }());
  63647. BABYLON.StringDictionary = StringDictionary;
  63648. })(BABYLON || (BABYLON = {}));
  63649. //# sourceMappingURL=babylon.stringDictionary.js.map
  63650. var BABYLON;
  63651. (function (BABYLON) {
  63652. var Tags = /** @class */ (function () {
  63653. function Tags() {
  63654. }
  63655. Tags.EnableFor = function (obj) {
  63656. obj._tags = obj._tags || {};
  63657. obj.hasTags = function () {
  63658. return Tags.HasTags(obj);
  63659. };
  63660. obj.addTags = function (tagsString) {
  63661. return Tags.AddTagsTo(obj, tagsString);
  63662. };
  63663. obj.removeTags = function (tagsString) {
  63664. return Tags.RemoveTagsFrom(obj, tagsString);
  63665. };
  63666. obj.matchesTagsQuery = function (tagsQuery) {
  63667. return Tags.MatchesQuery(obj, tagsQuery);
  63668. };
  63669. };
  63670. Tags.DisableFor = function (obj) {
  63671. delete obj._tags;
  63672. delete obj.hasTags;
  63673. delete obj.addTags;
  63674. delete obj.removeTags;
  63675. delete obj.matchesTagsQuery;
  63676. };
  63677. Tags.HasTags = function (obj) {
  63678. if (!obj._tags) {
  63679. return false;
  63680. }
  63681. return !BABYLON.Tools.IsEmpty(obj._tags);
  63682. };
  63683. Tags.GetTags = function (obj, asString) {
  63684. if (asString === void 0) { asString = true; }
  63685. if (!obj._tags) {
  63686. return null;
  63687. }
  63688. if (asString) {
  63689. var tagsArray = [];
  63690. for (var tag in obj._tags) {
  63691. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  63692. tagsArray.push(tag);
  63693. }
  63694. }
  63695. return tagsArray.join(" ");
  63696. }
  63697. else {
  63698. return obj._tags;
  63699. }
  63700. };
  63701. // the tags 'true' and 'false' are reserved and cannot be used as tags
  63702. // a tag cannot start with '||', '&&', and '!'
  63703. // it cannot contain whitespaces
  63704. Tags.AddTagsTo = function (obj, tagsString) {
  63705. if (!tagsString) {
  63706. return;
  63707. }
  63708. if (typeof tagsString !== "string") {
  63709. return;
  63710. }
  63711. var tags = tagsString.split(" ");
  63712. tags.forEach(function (tag, index, array) {
  63713. Tags._AddTagTo(obj, tag);
  63714. });
  63715. };
  63716. Tags._AddTagTo = function (obj, tag) {
  63717. tag = tag.trim();
  63718. if (tag === "" || tag === "true" || tag === "false") {
  63719. return;
  63720. }
  63721. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  63722. return;
  63723. }
  63724. Tags.EnableFor(obj);
  63725. obj._tags[tag] = true;
  63726. };
  63727. Tags.RemoveTagsFrom = function (obj, tagsString) {
  63728. if (!Tags.HasTags(obj)) {
  63729. return;
  63730. }
  63731. var tags = tagsString.split(" ");
  63732. for (var t in tags) {
  63733. Tags._RemoveTagFrom(obj, tags[t]);
  63734. }
  63735. };
  63736. Tags._RemoveTagFrom = function (obj, tag) {
  63737. delete obj._tags[tag];
  63738. };
  63739. Tags.MatchesQuery = function (obj, tagsQuery) {
  63740. if (tagsQuery === undefined) {
  63741. return true;
  63742. }
  63743. if (tagsQuery === "") {
  63744. return Tags.HasTags(obj);
  63745. }
  63746. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  63747. };
  63748. return Tags;
  63749. }());
  63750. BABYLON.Tags = Tags;
  63751. })(BABYLON || (BABYLON = {}));
  63752. //# sourceMappingURL=babylon.tags.js.map
  63753. var BABYLON;
  63754. (function (BABYLON) {
  63755. var AndOrNotEvaluator = /** @class */ (function () {
  63756. function AndOrNotEvaluator() {
  63757. }
  63758. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  63759. if (!query.match(/\([^\(\)]*\)/g)) {
  63760. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  63761. }
  63762. else {
  63763. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  63764. // remove parenthesis
  63765. r = r.slice(1, r.length - 1);
  63766. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  63767. });
  63768. }
  63769. if (query === "true") {
  63770. return true;
  63771. }
  63772. if (query === "false") {
  63773. return false;
  63774. }
  63775. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  63776. };
  63777. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  63778. evaluateCallback = evaluateCallback || (function (r) {
  63779. return r === "true" ? true : false;
  63780. });
  63781. var result;
  63782. var or = parenthesisContent.split("||");
  63783. for (var i in or) {
  63784. if (or.hasOwnProperty(i)) {
  63785. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  63786. var and = ori.split("&&");
  63787. if (and.length > 1) {
  63788. for (var j = 0; j < and.length; ++j) {
  63789. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  63790. if (andj !== "true" && andj !== "false") {
  63791. if (andj[0] === "!") {
  63792. result = !evaluateCallback(andj.substring(1));
  63793. }
  63794. else {
  63795. result = evaluateCallback(andj);
  63796. }
  63797. }
  63798. else {
  63799. result = andj === "true" ? true : false;
  63800. }
  63801. if (!result) {
  63802. ori = "false";
  63803. break;
  63804. }
  63805. }
  63806. }
  63807. if (result || ori === "true") {
  63808. result = true;
  63809. break;
  63810. }
  63811. // result equals false (or undefined)
  63812. if (ori !== "true" && ori !== "false") {
  63813. if (ori[0] === "!") {
  63814. result = !evaluateCallback(ori.substring(1));
  63815. }
  63816. else {
  63817. result = evaluateCallback(ori);
  63818. }
  63819. }
  63820. else {
  63821. result = ori === "true" ? true : false;
  63822. }
  63823. }
  63824. }
  63825. // the whole parenthesis scope is replaced by 'true' or 'false'
  63826. return result ? "true" : "false";
  63827. };
  63828. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  63829. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  63830. // remove whitespaces
  63831. r = r.replace(/[\s]/g, function () { return ""; });
  63832. return r.length % 2 ? "!" : "";
  63833. });
  63834. booleanString = booleanString.trim();
  63835. if (booleanString === "!true") {
  63836. booleanString = "false";
  63837. }
  63838. else if (booleanString === "!false") {
  63839. booleanString = "true";
  63840. }
  63841. return booleanString;
  63842. };
  63843. return AndOrNotEvaluator;
  63844. }());
  63845. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  63846. })(BABYLON || (BABYLON = {}));
  63847. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  63848. var BABYLON;
  63849. (function (BABYLON) {
  63850. var Database = /** @class */ (function () {
  63851. function Database(urlToScene, callbackManifestChecked) {
  63852. // Handling various flavors of prefixed version of IndexedDB
  63853. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  63854. this.callbackManifestChecked = callbackManifestChecked;
  63855. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  63856. this.db = null;
  63857. this._enableSceneOffline = false;
  63858. this._enableTexturesOffline = false;
  63859. this.manifestVersionFound = 0;
  63860. this.mustUpdateRessources = false;
  63861. this.hasReachedQuota = false;
  63862. if (!Database.IDBStorageEnabled) {
  63863. this.callbackManifestChecked(true);
  63864. }
  63865. else {
  63866. this.checkManifestFile();
  63867. }
  63868. }
  63869. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  63870. get: function () {
  63871. return this._enableSceneOffline;
  63872. },
  63873. enumerable: true,
  63874. configurable: true
  63875. });
  63876. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  63877. get: function () {
  63878. return this._enableTexturesOffline;
  63879. },
  63880. enumerable: true,
  63881. configurable: true
  63882. });
  63883. Database.prototype.checkManifestFile = function () {
  63884. var _this = this;
  63885. var noManifestFile = function () {
  63886. _this._enableSceneOffline = false;
  63887. _this._enableTexturesOffline = false;
  63888. _this.callbackManifestChecked(false);
  63889. };
  63890. var timeStampUsed = false;
  63891. var manifestURL = this.currentSceneUrl + ".manifest";
  63892. var xhr = new XMLHttpRequest();
  63893. if (navigator.onLine) {
  63894. // Adding a timestamp to by-pass browsers' cache
  63895. timeStampUsed = true;
  63896. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  63897. }
  63898. xhr.open("GET", manifestURL, true);
  63899. xhr.addEventListener("load", function () {
  63900. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  63901. try {
  63902. var manifestFile = JSON.parse(xhr.response);
  63903. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  63904. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  63905. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  63906. _this.manifestVersionFound = manifestFile.version;
  63907. }
  63908. if (_this.callbackManifestChecked) {
  63909. _this.callbackManifestChecked(true);
  63910. }
  63911. }
  63912. catch (ex) {
  63913. noManifestFile();
  63914. }
  63915. }
  63916. else {
  63917. noManifestFile();
  63918. }
  63919. }, false);
  63920. xhr.addEventListener("error", function (event) {
  63921. if (timeStampUsed) {
  63922. timeStampUsed = false;
  63923. // Let's retry without the timeStamp
  63924. // It could fail when coupled with HTML5 Offline API
  63925. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  63926. xhr.open("GET", retryManifestURL, true);
  63927. xhr.send();
  63928. }
  63929. else {
  63930. noManifestFile();
  63931. }
  63932. }, false);
  63933. try {
  63934. xhr.send();
  63935. }
  63936. catch (ex) {
  63937. BABYLON.Tools.Error("Error on XHR send request.");
  63938. this.callbackManifestChecked(false);
  63939. }
  63940. };
  63941. Database.prototype.openAsync = function (successCallback, errorCallback) {
  63942. var _this = this;
  63943. var handleError = function () {
  63944. _this.isSupported = false;
  63945. if (errorCallback)
  63946. errorCallback();
  63947. };
  63948. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  63949. // Your browser doesn't support IndexedDB
  63950. this.isSupported = false;
  63951. if (errorCallback)
  63952. errorCallback();
  63953. }
  63954. else {
  63955. // If the DB hasn't been opened or created yet
  63956. if (!this.db) {
  63957. this.hasReachedQuota = false;
  63958. this.isSupported = true;
  63959. var request = this.idbFactory.open("babylonjs", 1);
  63960. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  63961. request.onerror = function (event) {
  63962. handleError();
  63963. };
  63964. // executes when a version change transaction cannot complete due to other active transactions
  63965. request.onblocked = function (event) {
  63966. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  63967. handleError();
  63968. };
  63969. // DB has been opened successfully
  63970. request.onsuccess = function (event) {
  63971. _this.db = request.result;
  63972. successCallback();
  63973. };
  63974. // Initialization of the DB. Creating Scenes & Textures stores
  63975. request.onupgradeneeded = function (event) {
  63976. _this.db = (event.target).result;
  63977. if (_this.db) {
  63978. try {
  63979. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  63980. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  63981. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  63982. }
  63983. catch (ex) {
  63984. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  63985. handleError();
  63986. }
  63987. }
  63988. };
  63989. }
  63990. else {
  63991. if (successCallback)
  63992. successCallback();
  63993. }
  63994. }
  63995. };
  63996. Database.prototype.loadImageFromDB = function (url, image) {
  63997. var _this = this;
  63998. var completeURL = Database.ReturnFullUrlLocation(url);
  63999. var saveAndLoadImage = function () {
  64000. if (!_this.hasReachedQuota && _this.db !== null) {
  64001. // the texture is not yet in the DB, let's try to save it
  64002. _this._saveImageIntoDBAsync(completeURL, image);
  64003. }
  64004. else {
  64005. image.src = url;
  64006. }
  64007. };
  64008. if (!this.mustUpdateRessources) {
  64009. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  64010. }
  64011. else {
  64012. saveAndLoadImage();
  64013. }
  64014. };
  64015. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  64016. if (this.isSupported && this.db !== null) {
  64017. var texture;
  64018. var transaction = this.db.transaction(["textures"]);
  64019. transaction.onabort = function (event) {
  64020. image.src = url;
  64021. };
  64022. transaction.oncomplete = function (event) {
  64023. var blobTextureURL;
  64024. if (texture) {
  64025. var URL = window.URL || window.webkitURL;
  64026. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  64027. image.onerror = function () {
  64028. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  64029. image.src = url;
  64030. };
  64031. image.src = blobTextureURL;
  64032. }
  64033. else {
  64034. notInDBCallback();
  64035. }
  64036. };
  64037. var getRequest = transaction.objectStore("textures").get(url);
  64038. getRequest.onsuccess = function (event) {
  64039. texture = (event.target).result;
  64040. };
  64041. getRequest.onerror = function (event) {
  64042. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  64043. image.src = url;
  64044. };
  64045. }
  64046. else {
  64047. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64048. image.src = url;
  64049. }
  64050. };
  64051. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  64052. var _this = this;
  64053. if (this.isSupported) {
  64054. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  64055. var generateBlobUrl = function () {
  64056. var blobTextureURL;
  64057. if (blob) {
  64058. var URL = window.URL || window.webkitURL;
  64059. try {
  64060. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  64061. }
  64062. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  64063. catch (ex) {
  64064. blobTextureURL = URL.createObjectURL(blob);
  64065. }
  64066. }
  64067. if (blobTextureURL) {
  64068. image.src = blobTextureURL;
  64069. }
  64070. };
  64071. if (Database.IsUASupportingBlobStorage) {
  64072. var xhr = new XMLHttpRequest(), blob;
  64073. xhr.open("GET", url, true);
  64074. xhr.responseType = "blob";
  64075. xhr.addEventListener("load", function () {
  64076. if (xhr.status === 200 && _this.db) {
  64077. // Blob as response (XHR2)
  64078. blob = xhr.response;
  64079. var transaction = _this.db.transaction(["textures"], "readwrite");
  64080. // the transaction could abort because of a QuotaExceededError error
  64081. transaction.onabort = function (event) {
  64082. try {
  64083. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  64084. var srcElement = (event.srcElement || event.target);
  64085. var error = srcElement.error;
  64086. if (error && error.name === "QuotaExceededError") {
  64087. _this.hasReachedQuota = true;
  64088. }
  64089. }
  64090. catch (ex) { }
  64091. generateBlobUrl();
  64092. };
  64093. transaction.oncomplete = function (event) {
  64094. generateBlobUrl();
  64095. };
  64096. var newTexture = { textureUrl: url, data: blob };
  64097. try {
  64098. // Put the blob into the dabase
  64099. var addRequest = transaction.objectStore("textures").put(newTexture);
  64100. addRequest.onsuccess = function (event) {
  64101. };
  64102. addRequest.onerror = function (event) {
  64103. generateBlobUrl();
  64104. };
  64105. }
  64106. catch (ex) {
  64107. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  64108. if (ex.code === 25) {
  64109. Database.IsUASupportingBlobStorage = false;
  64110. }
  64111. image.src = url;
  64112. }
  64113. }
  64114. else {
  64115. image.src = url;
  64116. }
  64117. }, false);
  64118. xhr.addEventListener("error", function (event) {
  64119. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  64120. image.src = url;
  64121. }, false);
  64122. xhr.send();
  64123. }
  64124. else {
  64125. image.src = url;
  64126. }
  64127. }
  64128. else {
  64129. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64130. image.src = url;
  64131. }
  64132. };
  64133. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  64134. var _this = this;
  64135. var updateVersion = function () {
  64136. // the version is not yet in the DB or we need to update it
  64137. _this._saveVersionIntoDBAsync(url, versionLoaded);
  64138. };
  64139. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  64140. };
  64141. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  64142. var _this = this;
  64143. if (this.isSupported && this.db) {
  64144. var version;
  64145. try {
  64146. var transaction = this.db.transaction(["versions"]);
  64147. transaction.oncomplete = function (event) {
  64148. if (version) {
  64149. // If the version in the JSON file is > than the version in DB
  64150. if (_this.manifestVersionFound > version.data) {
  64151. _this.mustUpdateRessources = true;
  64152. updateInDBCallback();
  64153. }
  64154. else {
  64155. callback(version.data);
  64156. }
  64157. }
  64158. else {
  64159. _this.mustUpdateRessources = true;
  64160. updateInDBCallback();
  64161. }
  64162. };
  64163. transaction.onabort = function (event) {
  64164. callback(-1);
  64165. };
  64166. var getRequest = transaction.objectStore("versions").get(url);
  64167. getRequest.onsuccess = function (event) {
  64168. version = (event.target).result;
  64169. };
  64170. getRequest.onerror = function (event) {
  64171. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  64172. callback(-1);
  64173. };
  64174. }
  64175. catch (ex) {
  64176. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  64177. callback(-1);
  64178. }
  64179. }
  64180. else {
  64181. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64182. callback(-1);
  64183. }
  64184. };
  64185. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  64186. var _this = this;
  64187. if (this.isSupported && !this.hasReachedQuota && this.db) {
  64188. try {
  64189. // Open a transaction to the database
  64190. var transaction = this.db.transaction(["versions"], "readwrite");
  64191. // the transaction could abort because of a QuotaExceededError error
  64192. transaction.onabort = function (event) {
  64193. try {
  64194. var error = event.srcElement['error'];
  64195. if (error && error.name === "QuotaExceededError") {
  64196. _this.hasReachedQuota = true;
  64197. }
  64198. }
  64199. catch (ex) { }
  64200. callback(-1);
  64201. };
  64202. transaction.oncomplete = function (event) {
  64203. callback(_this.manifestVersionFound);
  64204. };
  64205. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  64206. // Put the scene into the database
  64207. var addRequest = transaction.objectStore("versions").put(newVersion);
  64208. addRequest.onsuccess = function (event) {
  64209. };
  64210. addRequest.onerror = function (event) {
  64211. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  64212. };
  64213. }
  64214. catch (ex) {
  64215. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  64216. callback(-1);
  64217. }
  64218. }
  64219. else {
  64220. callback(-1);
  64221. }
  64222. };
  64223. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  64224. var _this = this;
  64225. var completeUrl = Database.ReturnFullUrlLocation(url);
  64226. var saveAndLoadFile = function () {
  64227. // the scene is not yet in the DB, let's try to save it
  64228. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  64229. };
  64230. this._checkVersionFromDB(completeUrl, function (version) {
  64231. if (version !== -1) {
  64232. if (!_this.mustUpdateRessources) {
  64233. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  64234. }
  64235. else {
  64236. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  64237. }
  64238. }
  64239. else {
  64240. if (errorCallback) {
  64241. errorCallback();
  64242. }
  64243. }
  64244. });
  64245. };
  64246. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  64247. if (this.isSupported && this.db) {
  64248. var targetStore;
  64249. if (url.indexOf(".babylon") !== -1) {
  64250. targetStore = "scenes";
  64251. }
  64252. else {
  64253. targetStore = "textures";
  64254. }
  64255. var file;
  64256. var transaction = this.db.transaction([targetStore]);
  64257. transaction.oncomplete = function (event) {
  64258. if (file) {
  64259. callback(file.data);
  64260. }
  64261. else {
  64262. notInDBCallback();
  64263. }
  64264. };
  64265. transaction.onabort = function (event) {
  64266. notInDBCallback();
  64267. };
  64268. var getRequest = transaction.objectStore(targetStore).get(url);
  64269. getRequest.onsuccess = function (event) {
  64270. file = (event.target).result;
  64271. };
  64272. getRequest.onerror = function (event) {
  64273. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  64274. notInDBCallback();
  64275. };
  64276. }
  64277. else {
  64278. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64279. callback();
  64280. }
  64281. };
  64282. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  64283. var _this = this;
  64284. if (this.isSupported) {
  64285. var targetStore;
  64286. if (url.indexOf(".babylon") !== -1) {
  64287. targetStore = "scenes";
  64288. }
  64289. else {
  64290. targetStore = "textures";
  64291. }
  64292. // Create XHR
  64293. var xhr = new XMLHttpRequest();
  64294. var fileData;
  64295. xhr.open("GET", url, true);
  64296. if (useArrayBuffer) {
  64297. xhr.responseType = "arraybuffer";
  64298. }
  64299. if (progressCallback) {
  64300. xhr.onprogress = progressCallback;
  64301. }
  64302. xhr.addEventListener("load", function () {
  64303. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  64304. // Blob as response (XHR2)
  64305. //fileData = xhr.responseText;
  64306. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  64307. if (!_this.hasReachedQuota && _this.db) {
  64308. // Open a transaction to the database
  64309. var transaction = _this.db.transaction([targetStore], "readwrite");
  64310. // the transaction could abort because of a QuotaExceededError error
  64311. transaction.onabort = function (event) {
  64312. try {
  64313. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  64314. var error = event.srcElement['error'];
  64315. if (error && error.name === "QuotaExceededError") {
  64316. _this.hasReachedQuota = true;
  64317. }
  64318. }
  64319. catch (ex) { }
  64320. callback(fileData);
  64321. };
  64322. transaction.oncomplete = function (event) {
  64323. callback(fileData);
  64324. };
  64325. var newFile;
  64326. if (targetStore === "scenes") {
  64327. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  64328. }
  64329. else {
  64330. newFile = { textureUrl: url, data: fileData };
  64331. }
  64332. try {
  64333. // Put the scene into the database
  64334. var addRequest = transaction.objectStore(targetStore).put(newFile);
  64335. addRequest.onsuccess = function (event) {
  64336. };
  64337. addRequest.onerror = function (event) {
  64338. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  64339. };
  64340. }
  64341. catch (ex) {
  64342. callback(fileData);
  64343. }
  64344. }
  64345. else {
  64346. callback(fileData);
  64347. }
  64348. }
  64349. else {
  64350. callback();
  64351. }
  64352. }, false);
  64353. xhr.addEventListener("error", function (event) {
  64354. BABYLON.Tools.Error("error on XHR request.");
  64355. callback();
  64356. }, false);
  64357. xhr.send();
  64358. }
  64359. else {
  64360. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64361. callback();
  64362. }
  64363. };
  64364. Database.IsUASupportingBlobStorage = true;
  64365. Database.IDBStorageEnabled = true;
  64366. Database.parseURL = function (url) {
  64367. var a = document.createElement('a');
  64368. a.href = url;
  64369. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  64370. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  64371. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  64372. return absLocation;
  64373. };
  64374. Database.ReturnFullUrlLocation = function (url) {
  64375. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  64376. return (Database.parseURL(window.location.href) + url);
  64377. }
  64378. else {
  64379. return url;
  64380. }
  64381. };
  64382. return Database;
  64383. }());
  64384. BABYLON.Database = Database;
  64385. })(BABYLON || (BABYLON = {}));
  64386. //# sourceMappingURL=babylon.database.js.map
  64387. var BABYLON;
  64388. (function (BABYLON) {
  64389. var FresnelParameters = /** @class */ (function () {
  64390. function FresnelParameters() {
  64391. this._isEnabled = true;
  64392. this.leftColor = BABYLON.Color3.White();
  64393. this.rightColor = BABYLON.Color3.Black();
  64394. this.bias = 0;
  64395. this.power = 1;
  64396. }
  64397. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  64398. get: function () {
  64399. return this._isEnabled;
  64400. },
  64401. set: function (value) {
  64402. if (this._isEnabled === value) {
  64403. return;
  64404. }
  64405. this._isEnabled = value;
  64406. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  64407. },
  64408. enumerable: true,
  64409. configurable: true
  64410. });
  64411. FresnelParameters.prototype.clone = function () {
  64412. var newFresnelParameters = new FresnelParameters();
  64413. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  64414. return newFresnelParameters;
  64415. };
  64416. FresnelParameters.prototype.serialize = function () {
  64417. var serializationObject = {};
  64418. serializationObject.isEnabled = this.isEnabled;
  64419. serializationObject.leftColor = this.leftColor;
  64420. serializationObject.rightColor = this.rightColor;
  64421. serializationObject.bias = this.bias;
  64422. serializationObject.power = this.power;
  64423. return serializationObject;
  64424. };
  64425. FresnelParameters.Parse = function (parsedFresnelParameters) {
  64426. var fresnelParameters = new FresnelParameters();
  64427. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  64428. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  64429. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  64430. fresnelParameters.bias = parsedFresnelParameters.bias;
  64431. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  64432. return fresnelParameters;
  64433. };
  64434. return FresnelParameters;
  64435. }());
  64436. BABYLON.FresnelParameters = FresnelParameters;
  64437. })(BABYLON || (BABYLON = {}));
  64438. //# sourceMappingURL=babylon.fresnelParameters.js.map
  64439. var BABYLON;
  64440. (function (BABYLON) {
  64441. var MultiMaterial = /** @class */ (function (_super) {
  64442. __extends(MultiMaterial, _super);
  64443. function MultiMaterial(name, scene) {
  64444. var _this = _super.call(this, name, scene, true) || this;
  64445. scene.multiMaterials.push(_this);
  64446. _this.subMaterials = new Array();
  64447. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  64448. return _this;
  64449. }
  64450. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  64451. get: function () {
  64452. return this._subMaterials;
  64453. },
  64454. set: function (value) {
  64455. this._subMaterials = value;
  64456. this._hookArray(value);
  64457. },
  64458. enumerable: true,
  64459. configurable: true
  64460. });
  64461. MultiMaterial.prototype._hookArray = function (array) {
  64462. var _this = this;
  64463. var oldPush = array.push;
  64464. array.push = function () {
  64465. var items = [];
  64466. for (var _i = 0; _i < arguments.length; _i++) {
  64467. items[_i] = arguments[_i];
  64468. }
  64469. var result = oldPush.apply(array, items);
  64470. _this._markAllSubMeshesAsTexturesDirty();
  64471. return result;
  64472. };
  64473. var oldSplice = array.splice;
  64474. array.splice = function (index, deleteCount) {
  64475. var deleted = oldSplice.apply(array, [index, deleteCount]);
  64476. _this._markAllSubMeshesAsTexturesDirty();
  64477. return deleted;
  64478. };
  64479. };
  64480. // Properties
  64481. MultiMaterial.prototype.getSubMaterial = function (index) {
  64482. if (index < 0 || index >= this.subMaterials.length) {
  64483. return this.getScene().defaultMaterial;
  64484. }
  64485. return this.subMaterials[index];
  64486. };
  64487. MultiMaterial.prototype.getActiveTextures = function () {
  64488. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  64489. if (subMaterial) {
  64490. return subMaterial.getActiveTextures();
  64491. }
  64492. else {
  64493. return [];
  64494. }
  64495. }));
  64496. var _a;
  64497. };
  64498. // Methods
  64499. MultiMaterial.prototype.getClassName = function () {
  64500. return "MultiMaterial";
  64501. };
  64502. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  64503. for (var index = 0; index < this.subMaterials.length; index++) {
  64504. var subMaterial = this.subMaterials[index];
  64505. if (subMaterial) {
  64506. if (subMaterial.storeEffectOnSubMeshes) {
  64507. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  64508. return false;
  64509. }
  64510. continue;
  64511. }
  64512. if (!subMaterial.isReady(mesh)) {
  64513. return false;
  64514. }
  64515. }
  64516. }
  64517. return true;
  64518. };
  64519. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  64520. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  64521. for (var index = 0; index < this.subMaterials.length; index++) {
  64522. var subMaterial = null;
  64523. var current = this.subMaterials[index];
  64524. if (cloneChildren && current) {
  64525. subMaterial = current.clone(name + "-" + current.name);
  64526. }
  64527. else {
  64528. subMaterial = this.subMaterials[index];
  64529. }
  64530. newMultiMaterial.subMaterials.push(subMaterial);
  64531. }
  64532. return newMultiMaterial;
  64533. };
  64534. MultiMaterial.prototype.serialize = function () {
  64535. var serializationObject = {};
  64536. serializationObject.name = this.name;
  64537. serializationObject.id = this.id;
  64538. if (BABYLON.Tags) {
  64539. serializationObject.tags = BABYLON.Tags.GetTags(this);
  64540. }
  64541. serializationObject.materials = [];
  64542. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  64543. var subMat = this.subMaterials[matIndex];
  64544. if (subMat) {
  64545. serializationObject.materials.push(subMat.id);
  64546. }
  64547. else {
  64548. serializationObject.materials.push(null);
  64549. }
  64550. }
  64551. return serializationObject;
  64552. };
  64553. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  64554. var scene = this.getScene();
  64555. if (!scene) {
  64556. return;
  64557. }
  64558. var index = scene.multiMaterials.indexOf(this);
  64559. if (index >= 0) {
  64560. scene.multiMaterials.splice(index, 1);
  64561. }
  64562. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  64563. };
  64564. return MultiMaterial;
  64565. }(BABYLON.Material));
  64566. BABYLON.MultiMaterial = MultiMaterial;
  64567. })(BABYLON || (BABYLON = {}));
  64568. //# sourceMappingURL=babylon.multiMaterial.js.map
  64569. var BABYLON;
  64570. (function (BABYLON) {
  64571. var FreeCameraTouchInput = /** @class */ (function () {
  64572. function FreeCameraTouchInput() {
  64573. this._offsetX = null;
  64574. this._offsetY = null;
  64575. this._pointerPressed = new Array();
  64576. this.touchAngularSensibility = 200000.0;
  64577. this.touchMoveSensibility = 250.0;
  64578. }
  64579. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  64580. var _this = this;
  64581. var previousPosition = null;
  64582. if (this._pointerInput === undefined) {
  64583. this._onLostFocus = function (evt) {
  64584. _this._offsetX = null;
  64585. _this._offsetY = null;
  64586. };
  64587. this._pointerInput = function (p, s) {
  64588. var evt = p.event;
  64589. if (evt.pointerType === "mouse") {
  64590. return;
  64591. }
  64592. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  64593. if (!noPreventDefault) {
  64594. evt.preventDefault();
  64595. }
  64596. _this._pointerPressed.push(evt.pointerId);
  64597. if (_this._pointerPressed.length !== 1) {
  64598. return;
  64599. }
  64600. previousPosition = {
  64601. x: evt.clientX,
  64602. y: evt.clientY
  64603. };
  64604. }
  64605. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  64606. if (!noPreventDefault) {
  64607. evt.preventDefault();
  64608. }
  64609. var index = _this._pointerPressed.indexOf(evt.pointerId);
  64610. if (index === -1) {
  64611. return;
  64612. }
  64613. _this._pointerPressed.splice(index, 1);
  64614. if (index != 0) {
  64615. return;
  64616. }
  64617. previousPosition = null;
  64618. _this._offsetX = null;
  64619. _this._offsetY = null;
  64620. }
  64621. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  64622. if (!noPreventDefault) {
  64623. evt.preventDefault();
  64624. }
  64625. if (!previousPosition) {
  64626. return;
  64627. }
  64628. var index = _this._pointerPressed.indexOf(evt.pointerId);
  64629. if (index != 0) {
  64630. return;
  64631. }
  64632. _this._offsetX = evt.clientX - previousPosition.x;
  64633. _this._offsetY = -(evt.clientY - previousPosition.y);
  64634. }
  64635. };
  64636. }
  64637. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  64638. if (this._onLostFocus) {
  64639. element.addEventListener("blur", this._onLostFocus);
  64640. }
  64641. };
  64642. FreeCameraTouchInput.prototype.detachControl = function (element) {
  64643. if (this._pointerInput && element) {
  64644. if (this._observer) {
  64645. this.camera.getScene().onPointerObservable.remove(this._observer);
  64646. this._observer = null;
  64647. }
  64648. if (this._onLostFocus) {
  64649. element.removeEventListener("blur", this._onLostFocus);
  64650. this._onLostFocus = null;
  64651. }
  64652. this._pointerPressed = [];
  64653. this._offsetX = null;
  64654. this._offsetY = null;
  64655. }
  64656. };
  64657. FreeCameraTouchInput.prototype.checkInputs = function () {
  64658. if (this._offsetX && this._offsetY) {
  64659. var camera = this.camera;
  64660. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  64661. if (this._pointerPressed.length > 1) {
  64662. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  64663. }
  64664. else {
  64665. var speed = camera._computeLocalCameraSpeed();
  64666. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  64667. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  64668. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  64669. }
  64670. }
  64671. };
  64672. FreeCameraTouchInput.prototype.getClassName = function () {
  64673. return "FreeCameraTouchInput";
  64674. };
  64675. FreeCameraTouchInput.prototype.getSimpleName = function () {
  64676. return "touch";
  64677. };
  64678. __decorate([
  64679. BABYLON.serialize()
  64680. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  64681. __decorate([
  64682. BABYLON.serialize()
  64683. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  64684. return FreeCameraTouchInput;
  64685. }());
  64686. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  64687. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  64688. })(BABYLON || (BABYLON = {}));
  64689. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  64690. var BABYLON;
  64691. (function (BABYLON) {
  64692. // We're mainly based on the logic defined into the FreeCamera code
  64693. var TouchCamera = /** @class */ (function (_super) {
  64694. __extends(TouchCamera, _super);
  64695. //-- end properties for backward compatibility for inputs
  64696. function TouchCamera(name, position, scene) {
  64697. var _this = _super.call(this, name, position, scene) || this;
  64698. _this.inputs.addTouch();
  64699. _this._setupInputs();
  64700. return _this;
  64701. }
  64702. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  64703. //-- Begin properties for backward compatibility for inputs
  64704. get: function () {
  64705. var touch = this.inputs.attached["touch"];
  64706. if (touch)
  64707. return touch.touchAngularSensibility;
  64708. return 0;
  64709. },
  64710. set: function (value) {
  64711. var touch = this.inputs.attached["touch"];
  64712. if (touch)
  64713. touch.touchAngularSensibility = value;
  64714. },
  64715. enumerable: true,
  64716. configurable: true
  64717. });
  64718. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  64719. get: function () {
  64720. var touch = this.inputs.attached["touch"];
  64721. if (touch)
  64722. return touch.touchMoveSensibility;
  64723. return 0;
  64724. },
  64725. set: function (value) {
  64726. var touch = this.inputs.attached["touch"];
  64727. if (touch)
  64728. touch.touchMoveSensibility = value;
  64729. },
  64730. enumerable: true,
  64731. configurable: true
  64732. });
  64733. TouchCamera.prototype.getClassName = function () {
  64734. return "TouchCamera";
  64735. };
  64736. TouchCamera.prototype._setupInputs = function () {
  64737. var mouse = this.inputs.attached["mouse"];
  64738. if (mouse) {
  64739. mouse.touchEnabled = false;
  64740. }
  64741. };
  64742. return TouchCamera;
  64743. }(BABYLON.FreeCamera));
  64744. BABYLON.TouchCamera = TouchCamera;
  64745. })(BABYLON || (BABYLON = {}));
  64746. //# sourceMappingURL=babylon.touchCamera.js.map
  64747. var BABYLON;
  64748. (function (BABYLON) {
  64749. var ProceduralTexture = /** @class */ (function (_super) {
  64750. __extends(ProceduralTexture, _super);
  64751. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  64752. if (fallbackTexture === void 0) { fallbackTexture = null; }
  64753. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64754. if (isCube === void 0) { isCube = false; }
  64755. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  64756. _this.isCube = isCube;
  64757. _this.isEnabled = true;
  64758. _this._currentRefreshId = -1;
  64759. _this._refreshRate = 1;
  64760. _this._vertexBuffers = {};
  64761. _this._uniforms = new Array();
  64762. _this._samplers = new Array();
  64763. _this._textures = {};
  64764. _this._floats = {};
  64765. _this._floatsArrays = {};
  64766. _this._colors3 = {};
  64767. _this._colors4 = {};
  64768. _this._vectors2 = {};
  64769. _this._vectors3 = {};
  64770. _this._matrices = {};
  64771. _this._fallbackTextureUsed = false;
  64772. scene._proceduralTextures.push(_this);
  64773. _this._engine = scene.getEngine();
  64774. _this.name = name;
  64775. _this.isRenderTarget = true;
  64776. _this._size = size;
  64777. _this._generateMipMaps = generateMipMaps;
  64778. _this.setFragment(fragment);
  64779. _this._fallbackTexture = fallbackTexture;
  64780. if (isCube) {
  64781. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  64782. _this.setFloat("face", 0);
  64783. }
  64784. else {
  64785. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  64786. }
  64787. // VBO
  64788. var vertices = [];
  64789. vertices.push(1, 1);
  64790. vertices.push(-1, 1);
  64791. vertices.push(-1, -1);
  64792. vertices.push(1, -1);
  64793. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  64794. _this._createIndexBuffer();
  64795. return _this;
  64796. }
  64797. ProceduralTexture.prototype._createIndexBuffer = function () {
  64798. var engine = this._engine;
  64799. // Indices
  64800. var indices = [];
  64801. indices.push(0);
  64802. indices.push(1);
  64803. indices.push(2);
  64804. indices.push(0);
  64805. indices.push(2);
  64806. indices.push(3);
  64807. this._indexBuffer = engine.createIndexBuffer(indices);
  64808. };
  64809. ProceduralTexture.prototype._rebuild = function () {
  64810. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64811. if (vb) {
  64812. vb._rebuild();
  64813. }
  64814. this._createIndexBuffer();
  64815. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64816. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64817. }
  64818. };
  64819. ProceduralTexture.prototype.reset = function () {
  64820. if (this._effect === undefined) {
  64821. return;
  64822. }
  64823. var engine = this._engine;
  64824. engine._releaseEffect(this._effect);
  64825. };
  64826. ProceduralTexture.prototype.isReady = function () {
  64827. var _this = this;
  64828. var engine = this._engine;
  64829. var shaders;
  64830. if (!this._fragment) {
  64831. return false;
  64832. }
  64833. if (this._fallbackTextureUsed) {
  64834. return true;
  64835. }
  64836. if (this._fragment.fragmentElement !== undefined) {
  64837. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  64838. }
  64839. else {
  64840. shaders = { vertex: "procedural", fragment: this._fragment };
  64841. }
  64842. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  64843. _this.releaseInternalTexture();
  64844. if (_this._fallbackTexture) {
  64845. _this._texture = _this._fallbackTexture._texture;
  64846. if (_this._texture) {
  64847. _this._texture.incrementReferences();
  64848. }
  64849. }
  64850. _this._fallbackTextureUsed = true;
  64851. });
  64852. return this._effect.isReady();
  64853. };
  64854. ProceduralTexture.prototype.resetRefreshCounter = function () {
  64855. this._currentRefreshId = -1;
  64856. };
  64857. ProceduralTexture.prototype.setFragment = function (fragment) {
  64858. this._fragment = fragment;
  64859. };
  64860. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  64861. get: function () {
  64862. return this._refreshRate;
  64863. },
  64864. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  64865. set: function (value) {
  64866. this._refreshRate = value;
  64867. this.resetRefreshCounter();
  64868. },
  64869. enumerable: true,
  64870. configurable: true
  64871. });
  64872. ProceduralTexture.prototype._shouldRender = function () {
  64873. if (!this.isEnabled || !this.isReady() || !this._texture) {
  64874. return false;
  64875. }
  64876. if (this._fallbackTextureUsed) {
  64877. return false;
  64878. }
  64879. if (this._currentRefreshId === -1) {
  64880. this._currentRefreshId = 1;
  64881. return true;
  64882. }
  64883. if (this.refreshRate === this._currentRefreshId) {
  64884. this._currentRefreshId = 1;
  64885. return true;
  64886. }
  64887. this._currentRefreshId++;
  64888. return false;
  64889. };
  64890. ProceduralTexture.prototype.getRenderSize = function () {
  64891. return this._size;
  64892. };
  64893. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  64894. if (this._fallbackTextureUsed) {
  64895. return;
  64896. }
  64897. this.releaseInternalTexture();
  64898. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  64899. };
  64900. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  64901. if (this._uniforms.indexOf(uniformName) === -1) {
  64902. this._uniforms.push(uniformName);
  64903. }
  64904. };
  64905. ProceduralTexture.prototype.setTexture = function (name, texture) {
  64906. if (this._samplers.indexOf(name) === -1) {
  64907. this._samplers.push(name);
  64908. }
  64909. this._textures[name] = texture;
  64910. return this;
  64911. };
  64912. ProceduralTexture.prototype.setFloat = function (name, value) {
  64913. this._checkUniform(name);
  64914. this._floats[name] = value;
  64915. return this;
  64916. };
  64917. ProceduralTexture.prototype.setFloats = function (name, value) {
  64918. this._checkUniform(name);
  64919. this._floatsArrays[name] = value;
  64920. return this;
  64921. };
  64922. ProceduralTexture.prototype.setColor3 = function (name, value) {
  64923. this._checkUniform(name);
  64924. this._colors3[name] = value;
  64925. return this;
  64926. };
  64927. ProceduralTexture.prototype.setColor4 = function (name, value) {
  64928. this._checkUniform(name);
  64929. this._colors4[name] = value;
  64930. return this;
  64931. };
  64932. ProceduralTexture.prototype.setVector2 = function (name, value) {
  64933. this._checkUniform(name);
  64934. this._vectors2[name] = value;
  64935. return this;
  64936. };
  64937. ProceduralTexture.prototype.setVector3 = function (name, value) {
  64938. this._checkUniform(name);
  64939. this._vectors3[name] = value;
  64940. return this;
  64941. };
  64942. ProceduralTexture.prototype.setMatrix = function (name, value) {
  64943. this._checkUniform(name);
  64944. this._matrices[name] = value;
  64945. return this;
  64946. };
  64947. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  64948. var scene = this.getScene();
  64949. if (!scene) {
  64950. return;
  64951. }
  64952. var engine = this._engine;
  64953. // Render
  64954. engine.enableEffect(this._effect);
  64955. engine.setState(false);
  64956. // Texture
  64957. for (var name in this._textures) {
  64958. this._effect.setTexture(name, this._textures[name]);
  64959. }
  64960. // Float
  64961. for (name in this._floats) {
  64962. this._effect.setFloat(name, this._floats[name]);
  64963. }
  64964. // Floats
  64965. for (name in this._floatsArrays) {
  64966. this._effect.setArray(name, this._floatsArrays[name]);
  64967. }
  64968. // Color3
  64969. for (name in this._colors3) {
  64970. this._effect.setColor3(name, this._colors3[name]);
  64971. }
  64972. // Color4
  64973. for (name in this._colors4) {
  64974. var color = this._colors4[name];
  64975. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  64976. }
  64977. // Vector2
  64978. for (name in this._vectors2) {
  64979. this._effect.setVector2(name, this._vectors2[name]);
  64980. }
  64981. // Vector3
  64982. for (name in this._vectors3) {
  64983. this._effect.setVector3(name, this._vectors3[name]);
  64984. }
  64985. // Matrix
  64986. for (name in this._matrices) {
  64987. this._effect.setMatrix(name, this._matrices[name]);
  64988. }
  64989. if (!this._texture) {
  64990. return;
  64991. }
  64992. if (this.isCube) {
  64993. for (var face = 0; face < 6; face++) {
  64994. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  64995. // VBOs
  64996. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  64997. this._effect.setFloat("face", face);
  64998. // Clear
  64999. engine.clear(scene.clearColor, true, true, true);
  65000. // Draw order
  65001. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65002. // Mipmaps
  65003. if (face === 5) {
  65004. engine.generateMipMapsForCubemap(this._texture);
  65005. }
  65006. }
  65007. }
  65008. else {
  65009. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  65010. // VBOs
  65011. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  65012. // Clear
  65013. engine.clear(scene.clearColor, true, true, true);
  65014. // Draw order
  65015. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65016. }
  65017. // Unbind
  65018. engine.unBindFramebuffer(this._texture, this.isCube);
  65019. if (this.onGenerated) {
  65020. this.onGenerated();
  65021. }
  65022. };
  65023. ProceduralTexture.prototype.clone = function () {
  65024. var textureSize = this.getSize();
  65025. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  65026. // Base texture
  65027. newTexture.hasAlpha = this.hasAlpha;
  65028. newTexture.level = this.level;
  65029. // RenderTarget Texture
  65030. newTexture.coordinatesMode = this.coordinatesMode;
  65031. return newTexture;
  65032. };
  65033. ProceduralTexture.prototype.dispose = function () {
  65034. var scene = this.getScene();
  65035. if (!scene) {
  65036. return;
  65037. }
  65038. var index = scene._proceduralTextures.indexOf(this);
  65039. if (index >= 0) {
  65040. scene._proceduralTextures.splice(index, 1);
  65041. }
  65042. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65043. if (vertexBuffer) {
  65044. vertexBuffer.dispose();
  65045. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65046. }
  65047. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  65048. this._indexBuffer = null;
  65049. }
  65050. _super.prototype.dispose.call(this);
  65051. };
  65052. return ProceduralTexture;
  65053. }(BABYLON.Texture));
  65054. BABYLON.ProceduralTexture = ProceduralTexture;
  65055. })(BABYLON || (BABYLON = {}));
  65056. //# sourceMappingURL=babylon.proceduralTexture.js.map
  65057. var BABYLON;
  65058. (function (BABYLON) {
  65059. var CustomProceduralTexture = /** @class */ (function (_super) {
  65060. __extends(CustomProceduralTexture, _super);
  65061. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  65062. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  65063. _this._animate = true;
  65064. _this._time = 0;
  65065. _this._texturePath = texturePath;
  65066. //Try to load json
  65067. _this.loadJson(texturePath);
  65068. _this.refreshRate = 1;
  65069. return _this;
  65070. }
  65071. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  65072. var _this = this;
  65073. var noConfigFile = function () {
  65074. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  65075. try {
  65076. _this.setFragment(_this._texturePath);
  65077. }
  65078. catch (ex) {
  65079. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  65080. }
  65081. };
  65082. var configFileUrl = jsonUrl + "/config.json";
  65083. var xhr = new XMLHttpRequest();
  65084. xhr.open("GET", configFileUrl, true);
  65085. xhr.addEventListener("load", function () {
  65086. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  65087. try {
  65088. _this._config = JSON.parse(xhr.response);
  65089. _this.updateShaderUniforms();
  65090. _this.updateTextures();
  65091. _this.setFragment(_this._texturePath + "/custom");
  65092. _this._animate = _this._config.animate;
  65093. _this.refreshRate = _this._config.refreshrate;
  65094. }
  65095. catch (ex) {
  65096. noConfigFile();
  65097. }
  65098. }
  65099. else {
  65100. noConfigFile();
  65101. }
  65102. }, false);
  65103. xhr.addEventListener("error", function () {
  65104. noConfigFile();
  65105. }, false);
  65106. try {
  65107. xhr.send();
  65108. }
  65109. catch (ex) {
  65110. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  65111. }
  65112. };
  65113. CustomProceduralTexture.prototype.isReady = function () {
  65114. if (!_super.prototype.isReady.call(this)) {
  65115. return false;
  65116. }
  65117. for (var name in this._textures) {
  65118. var texture = this._textures[name];
  65119. if (!texture.isReady()) {
  65120. return false;
  65121. }
  65122. }
  65123. return true;
  65124. };
  65125. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  65126. var scene = this.getScene();
  65127. if (this._animate && scene) {
  65128. this._time += scene.getAnimationRatio() * 0.03;
  65129. this.updateShaderUniforms();
  65130. }
  65131. _super.prototype.render.call(this, useCameraPostProcess);
  65132. };
  65133. CustomProceduralTexture.prototype.updateTextures = function () {
  65134. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  65135. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  65136. }
  65137. };
  65138. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  65139. if (this._config) {
  65140. for (var j = 0; j < this._config.uniforms.length; j++) {
  65141. var uniform = this._config.uniforms[j];
  65142. switch (uniform.type) {
  65143. case "float":
  65144. this.setFloat(uniform.name, uniform.value);
  65145. break;
  65146. case "color3":
  65147. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  65148. break;
  65149. case "color4":
  65150. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  65151. break;
  65152. case "vector2":
  65153. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  65154. break;
  65155. case "vector3":
  65156. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  65157. break;
  65158. }
  65159. }
  65160. }
  65161. this.setFloat("time", this._time);
  65162. };
  65163. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  65164. get: function () {
  65165. return this._animate;
  65166. },
  65167. set: function (value) {
  65168. this._animate = value;
  65169. },
  65170. enumerable: true,
  65171. configurable: true
  65172. });
  65173. return CustomProceduralTexture;
  65174. }(BABYLON.ProceduralTexture));
  65175. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  65176. })(BABYLON || (BABYLON = {}));
  65177. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  65178. var BABYLON;
  65179. (function (BABYLON) {
  65180. var FreeCameraGamepadInput = /** @class */ (function () {
  65181. function FreeCameraGamepadInput() {
  65182. this.gamepadAngularSensibility = 200;
  65183. this.gamepadMoveSensibility = 40;
  65184. // private members
  65185. this._cameraTransform = BABYLON.Matrix.Identity();
  65186. this._deltaTransform = BABYLON.Vector3.Zero();
  65187. this._vector3 = BABYLON.Vector3.Zero();
  65188. this._vector2 = BABYLON.Vector2.Zero();
  65189. }
  65190. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  65191. var _this = this;
  65192. var manager = this.camera.getScene().gamepadManager;
  65193. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  65194. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  65195. // prioritize XBOX gamepads.
  65196. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  65197. _this.gamepad = gamepad;
  65198. }
  65199. }
  65200. });
  65201. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  65202. if (_this.gamepad === gamepad) {
  65203. _this.gamepad = null;
  65204. }
  65205. });
  65206. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  65207. };
  65208. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  65209. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  65210. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  65211. this.gamepad = null;
  65212. };
  65213. FreeCameraGamepadInput.prototype.checkInputs = function () {
  65214. if (this.gamepad && this.gamepad.leftStick) {
  65215. var camera = this.camera;
  65216. var LSValues = this.gamepad.leftStick;
  65217. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  65218. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  65219. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  65220. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  65221. var RSValues = this.gamepad.rightStick;
  65222. if (RSValues) {
  65223. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  65224. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  65225. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  65226. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  65227. }
  65228. else {
  65229. RSValues = { x: 0, y: 0 };
  65230. }
  65231. if (!camera.rotationQuaternion) {
  65232. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  65233. }
  65234. else {
  65235. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  65236. }
  65237. var speed = camera._computeLocalCameraSpeed() * 50.0;
  65238. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  65239. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  65240. camera.cameraDirection.addInPlace(this._deltaTransform);
  65241. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  65242. camera.cameraRotation.addInPlace(this._vector2);
  65243. }
  65244. };
  65245. FreeCameraGamepadInput.prototype.getClassName = function () {
  65246. return "FreeCameraGamepadInput";
  65247. };
  65248. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  65249. return "gamepad";
  65250. };
  65251. __decorate([
  65252. BABYLON.serialize()
  65253. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  65254. __decorate([
  65255. BABYLON.serialize()
  65256. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  65257. return FreeCameraGamepadInput;
  65258. }());
  65259. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  65260. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  65261. })(BABYLON || (BABYLON = {}));
  65262. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  65263. var BABYLON;
  65264. (function (BABYLON) {
  65265. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  65266. function ArcRotateCameraGamepadInput() {
  65267. this.gamepadRotationSensibility = 80;
  65268. this.gamepadMoveSensibility = 40;
  65269. }
  65270. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  65271. var _this = this;
  65272. var manager = this.camera.getScene().gamepadManager;
  65273. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  65274. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  65275. // prioritize XBOX gamepads.
  65276. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  65277. _this.gamepad = gamepad;
  65278. }
  65279. }
  65280. });
  65281. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  65282. if (_this.gamepad === gamepad) {
  65283. _this.gamepad = null;
  65284. }
  65285. });
  65286. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  65287. };
  65288. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  65289. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  65290. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  65291. this.gamepad = null;
  65292. };
  65293. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  65294. if (this.gamepad) {
  65295. var camera = this.camera;
  65296. var RSValues = this.gamepad.rightStick;
  65297. if (RSValues) {
  65298. if (RSValues.x != 0) {
  65299. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  65300. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  65301. camera.inertialAlphaOffset += normalizedRX;
  65302. }
  65303. }
  65304. if (RSValues.y != 0) {
  65305. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  65306. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  65307. camera.inertialBetaOffset += normalizedRY;
  65308. }
  65309. }
  65310. }
  65311. var LSValues = this.gamepad.leftStick;
  65312. if (LSValues && LSValues.y != 0) {
  65313. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  65314. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  65315. this.camera.inertialRadiusOffset -= normalizedLY;
  65316. }
  65317. }
  65318. }
  65319. };
  65320. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  65321. return "ArcRotateCameraGamepadInput";
  65322. };
  65323. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  65324. return "gamepad";
  65325. };
  65326. __decorate([
  65327. BABYLON.serialize()
  65328. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  65329. __decorate([
  65330. BABYLON.serialize()
  65331. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  65332. return ArcRotateCameraGamepadInput;
  65333. }());
  65334. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  65335. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  65336. })(BABYLON || (BABYLON = {}));
  65337. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  65338. var BABYLON;
  65339. (function (BABYLON) {
  65340. var GamepadManager = /** @class */ (function () {
  65341. function GamepadManager(_scene) {
  65342. var _this = this;
  65343. this._scene = _scene;
  65344. this._babylonGamepads = [];
  65345. this._oneGamepadConnected = false;
  65346. this._isMonitoring = false;
  65347. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  65348. if (!BABYLON.Tools.IsWindowObjectExist()) {
  65349. this._gamepadEventSupported = false;
  65350. }
  65351. else {
  65352. this._gamepadEventSupported = 'GamepadEvent' in window;
  65353. this._gamepadSupport = (navigator.getGamepads ||
  65354. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  65355. }
  65356. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  65357. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  65358. for (var i in _this._babylonGamepads) {
  65359. var gamepad = _this._babylonGamepads[i];
  65360. if (gamepad && gamepad._isConnected) {
  65361. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  65362. }
  65363. }
  65364. });
  65365. this._onGamepadConnectedEvent = function (evt) {
  65366. var gamepad = evt.gamepad;
  65367. if (gamepad.index in _this._babylonGamepads) {
  65368. if (_this._babylonGamepads[gamepad.index].isConnected) {
  65369. return;
  65370. }
  65371. }
  65372. var newGamepad;
  65373. if (_this._babylonGamepads[gamepad.index]) {
  65374. newGamepad = _this._babylonGamepads[gamepad.index];
  65375. newGamepad.browserGamepad = gamepad;
  65376. newGamepad._isConnected = true;
  65377. }
  65378. else {
  65379. newGamepad = _this._addNewGamepad(gamepad);
  65380. }
  65381. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  65382. _this._startMonitoringGamepads();
  65383. };
  65384. this._onGamepadDisconnectedEvent = function (evt) {
  65385. var gamepad = evt.gamepad;
  65386. // Remove the gamepad from the list of gamepads to monitor.
  65387. for (var i in _this._babylonGamepads) {
  65388. if (_this._babylonGamepads[i].index === gamepad.index) {
  65389. var disconnectedGamepad = _this._babylonGamepads[i];
  65390. disconnectedGamepad._isConnected = false;
  65391. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  65392. break;
  65393. }
  65394. }
  65395. };
  65396. if (this._gamepadSupport) {
  65397. //first add already-connected gamepads
  65398. this._updateGamepadObjects();
  65399. if (this._babylonGamepads.length) {
  65400. this._startMonitoringGamepads();
  65401. }
  65402. // Checking if the gamepad connected event is supported (like in Firefox)
  65403. if (this._gamepadEventSupported) {
  65404. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  65405. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  65406. }
  65407. else {
  65408. this._startMonitoringGamepads();
  65409. }
  65410. }
  65411. }
  65412. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  65413. get: function () {
  65414. return this._babylonGamepads;
  65415. },
  65416. enumerable: true,
  65417. configurable: true
  65418. });
  65419. GamepadManager.prototype.getGamepadByType = function (type) {
  65420. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  65421. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  65422. var gamepad = _a[_i];
  65423. if (gamepad && gamepad.type === type) {
  65424. return gamepad;
  65425. }
  65426. }
  65427. return null;
  65428. };
  65429. GamepadManager.prototype.dispose = function () {
  65430. if (this._gamepadEventSupported) {
  65431. if (this._onGamepadConnectedEvent) {
  65432. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  65433. }
  65434. if (this._onGamepadDisconnectedEvent) {
  65435. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  65436. }
  65437. this._onGamepadConnectedEvent = null;
  65438. this._onGamepadDisconnectedEvent = null;
  65439. }
  65440. this._babylonGamepads.forEach(function (gamepad) {
  65441. gamepad.dispose();
  65442. });
  65443. this.onGamepadConnectedObservable.clear();
  65444. this.onGamepadDisconnectedObservable.clear();
  65445. this._oneGamepadConnected = false;
  65446. this._stopMonitoringGamepads();
  65447. this._babylonGamepads = [];
  65448. };
  65449. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  65450. if (!this._oneGamepadConnected) {
  65451. this._oneGamepadConnected = true;
  65452. }
  65453. var newGamepad;
  65454. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  65455. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  65456. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  65457. }
  65458. else if (gamepad.pose) {
  65459. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  65460. }
  65461. else {
  65462. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  65463. }
  65464. this._babylonGamepads[newGamepad.index] = newGamepad;
  65465. return newGamepad;
  65466. };
  65467. GamepadManager.prototype._startMonitoringGamepads = function () {
  65468. if (!this._isMonitoring) {
  65469. this._isMonitoring = true;
  65470. //back-comp
  65471. if (!this._scene) {
  65472. this._checkGamepadsStatus();
  65473. }
  65474. }
  65475. };
  65476. GamepadManager.prototype._stopMonitoringGamepads = function () {
  65477. this._isMonitoring = false;
  65478. };
  65479. GamepadManager.prototype._checkGamepadsStatus = function () {
  65480. var _this = this;
  65481. // Hack to be compatible Chrome
  65482. this._updateGamepadObjects();
  65483. for (var i in this._babylonGamepads) {
  65484. var gamepad = this._babylonGamepads[i];
  65485. if (!gamepad || !gamepad.isConnected) {
  65486. continue;
  65487. }
  65488. gamepad.update();
  65489. }
  65490. if (this._isMonitoring && !this._scene) {
  65491. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  65492. }
  65493. };
  65494. // This function is called only on Chrome, which does not properly support
  65495. // connection/disconnection events and forces you to recopy again the gamepad object
  65496. GamepadManager.prototype._updateGamepadObjects = function () {
  65497. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  65498. for (var i = 0; i < gamepads.length; i++) {
  65499. if (gamepads[i]) {
  65500. if (!this._babylonGamepads[gamepads[i].index]) {
  65501. var newGamepad = this._addNewGamepad(gamepads[i]);
  65502. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  65503. }
  65504. else {
  65505. // Forced to copy again this object for Chrome for unknown reason
  65506. this._babylonGamepads[i].browserGamepad = gamepads[i];
  65507. if (!this._babylonGamepads[i].isConnected) {
  65508. this._babylonGamepads[i]._isConnected = true;
  65509. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  65510. }
  65511. }
  65512. }
  65513. }
  65514. };
  65515. return GamepadManager;
  65516. }());
  65517. BABYLON.GamepadManager = GamepadManager;
  65518. })(BABYLON || (BABYLON = {}));
  65519. //# sourceMappingURL=babylon.gamepadManager.js.map
  65520. var BABYLON;
  65521. (function (BABYLON) {
  65522. var StickValues = /** @class */ (function () {
  65523. function StickValues(x, y) {
  65524. this.x = x;
  65525. this.y = y;
  65526. }
  65527. return StickValues;
  65528. }());
  65529. BABYLON.StickValues = StickValues;
  65530. var Gamepad = /** @class */ (function () {
  65531. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  65532. if (leftStickX === void 0) { leftStickX = 0; }
  65533. if (leftStickY === void 0) { leftStickY = 1; }
  65534. if (rightStickX === void 0) { rightStickX = 2; }
  65535. if (rightStickY === void 0) { rightStickY = 3; }
  65536. this.id = id;
  65537. this.index = index;
  65538. this.browserGamepad = browserGamepad;
  65539. this._isConnected = true;
  65540. this._invertLeftStickY = false;
  65541. this.type = Gamepad.GAMEPAD;
  65542. this._leftStickAxisX = leftStickX;
  65543. this._leftStickAxisY = leftStickY;
  65544. this._rightStickAxisX = rightStickX;
  65545. this._rightStickAxisY = rightStickY;
  65546. if (this.browserGamepad.axes.length >= 2) {
  65547. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  65548. }
  65549. if (this.browserGamepad.axes.length >= 4) {
  65550. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  65551. }
  65552. }
  65553. Object.defineProperty(Gamepad.prototype, "isConnected", {
  65554. get: function () {
  65555. return this._isConnected;
  65556. },
  65557. enumerable: true,
  65558. configurable: true
  65559. });
  65560. Gamepad.prototype.onleftstickchanged = function (callback) {
  65561. this._onleftstickchanged = callback;
  65562. };
  65563. Gamepad.prototype.onrightstickchanged = function (callback) {
  65564. this._onrightstickchanged = callback;
  65565. };
  65566. Object.defineProperty(Gamepad.prototype, "leftStick", {
  65567. get: function () {
  65568. return this._leftStick;
  65569. },
  65570. set: function (newValues) {
  65571. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  65572. this._onleftstickchanged(newValues);
  65573. }
  65574. this._leftStick = newValues;
  65575. },
  65576. enumerable: true,
  65577. configurable: true
  65578. });
  65579. Object.defineProperty(Gamepad.prototype, "rightStick", {
  65580. get: function () {
  65581. return this._rightStick;
  65582. },
  65583. set: function (newValues) {
  65584. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  65585. this._onrightstickchanged(newValues);
  65586. }
  65587. this._rightStick = newValues;
  65588. },
  65589. enumerable: true,
  65590. configurable: true
  65591. });
  65592. Gamepad.prototype.update = function () {
  65593. if (this._leftStick) {
  65594. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  65595. if (this._invertLeftStickY) {
  65596. this.leftStick.y *= -1;
  65597. }
  65598. }
  65599. if (this._rightStick) {
  65600. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  65601. }
  65602. };
  65603. Gamepad.prototype.dispose = function () {
  65604. };
  65605. Gamepad.GAMEPAD = 0;
  65606. Gamepad.GENERIC = 1;
  65607. Gamepad.XBOX = 2;
  65608. Gamepad.POSE_ENABLED = 3;
  65609. return Gamepad;
  65610. }());
  65611. BABYLON.Gamepad = Gamepad;
  65612. var GenericPad = /** @class */ (function (_super) {
  65613. __extends(GenericPad, _super);
  65614. function GenericPad(id, index, browserGamepad) {
  65615. var _this = _super.call(this, id, index, browserGamepad) || this;
  65616. _this.onButtonDownObservable = new BABYLON.Observable();
  65617. _this.onButtonUpObservable = new BABYLON.Observable();
  65618. _this.type = Gamepad.GENERIC;
  65619. _this._buttons = new Array(browserGamepad.buttons.length);
  65620. return _this;
  65621. }
  65622. GenericPad.prototype.onbuttondown = function (callback) {
  65623. this._onbuttondown = callback;
  65624. };
  65625. GenericPad.prototype.onbuttonup = function (callback) {
  65626. this._onbuttonup = callback;
  65627. };
  65628. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  65629. if (newValue !== currentValue) {
  65630. if (newValue === 1) {
  65631. if (this._onbuttondown) {
  65632. this._onbuttondown(buttonIndex);
  65633. }
  65634. this.onButtonDownObservable.notifyObservers(buttonIndex);
  65635. }
  65636. if (newValue === 0) {
  65637. if (this._onbuttonup) {
  65638. this._onbuttonup(buttonIndex);
  65639. }
  65640. this.onButtonUpObservable.notifyObservers(buttonIndex);
  65641. }
  65642. }
  65643. return newValue;
  65644. };
  65645. GenericPad.prototype.update = function () {
  65646. _super.prototype.update.call(this);
  65647. for (var index = 0; index < this._buttons.length; index++) {
  65648. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  65649. }
  65650. };
  65651. GenericPad.prototype.dispose = function () {
  65652. _super.prototype.dispose.call(this);
  65653. this.onButtonDownObservable.clear();
  65654. this.onButtonUpObservable.clear();
  65655. };
  65656. return GenericPad;
  65657. }(Gamepad));
  65658. BABYLON.GenericPad = GenericPad;
  65659. })(BABYLON || (BABYLON = {}));
  65660. //# sourceMappingURL=babylon.gamepad.js.map
  65661. var BABYLON;
  65662. (function (BABYLON) {
  65663. var Xbox360Button;
  65664. (function (Xbox360Button) {
  65665. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  65666. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  65667. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  65668. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  65669. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  65670. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  65671. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  65672. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  65673. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  65674. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  65675. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  65676. var Xbox360Dpad;
  65677. (function (Xbox360Dpad) {
  65678. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  65679. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  65680. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  65681. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  65682. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  65683. var Xbox360Pad = /** @class */ (function (_super) {
  65684. __extends(Xbox360Pad, _super);
  65685. function Xbox360Pad(id, index, gamepad, xboxOne) {
  65686. if (xboxOne === void 0) { xboxOne = false; }
  65687. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  65688. _this._leftTrigger = 0;
  65689. _this._rightTrigger = 0;
  65690. _this.onButtonDownObservable = new BABYLON.Observable();
  65691. _this.onButtonUpObservable = new BABYLON.Observable();
  65692. _this.onPadDownObservable = new BABYLON.Observable();
  65693. _this.onPadUpObservable = new BABYLON.Observable();
  65694. _this._buttonA = 0;
  65695. _this._buttonB = 0;
  65696. _this._buttonX = 0;
  65697. _this._buttonY = 0;
  65698. _this._buttonBack = 0;
  65699. _this._buttonStart = 0;
  65700. _this._buttonLB = 0;
  65701. _this._buttonRB = 0;
  65702. _this._buttonLeftStick = 0;
  65703. _this._buttonRightStick = 0;
  65704. _this._dPadUp = 0;
  65705. _this._dPadDown = 0;
  65706. _this._dPadLeft = 0;
  65707. _this._dPadRight = 0;
  65708. _this._isXboxOnePad = false;
  65709. _this.type = BABYLON.Gamepad.XBOX;
  65710. _this._isXboxOnePad = xboxOne;
  65711. return _this;
  65712. }
  65713. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  65714. this._onlefttriggerchanged = callback;
  65715. };
  65716. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  65717. this._onrighttriggerchanged = callback;
  65718. };
  65719. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  65720. get: function () {
  65721. return this._leftTrigger;
  65722. },
  65723. set: function (newValue) {
  65724. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  65725. this._onlefttriggerchanged(newValue);
  65726. }
  65727. this._leftTrigger = newValue;
  65728. },
  65729. enumerable: true,
  65730. configurable: true
  65731. });
  65732. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  65733. get: function () {
  65734. return this._rightTrigger;
  65735. },
  65736. set: function (newValue) {
  65737. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  65738. this._onrighttriggerchanged(newValue);
  65739. }
  65740. this._rightTrigger = newValue;
  65741. },
  65742. enumerable: true,
  65743. configurable: true
  65744. });
  65745. Xbox360Pad.prototype.onbuttondown = function (callback) {
  65746. this._onbuttondown = callback;
  65747. };
  65748. Xbox360Pad.prototype.onbuttonup = function (callback) {
  65749. this._onbuttonup = callback;
  65750. };
  65751. Xbox360Pad.prototype.ondpaddown = function (callback) {
  65752. this._ondpaddown = callback;
  65753. };
  65754. Xbox360Pad.prototype.ondpadup = function (callback) {
  65755. this._ondpadup = callback;
  65756. };
  65757. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  65758. if (newValue !== currentValue) {
  65759. if (newValue === 1) {
  65760. if (this._onbuttondown) {
  65761. this._onbuttondown(buttonType);
  65762. }
  65763. this.onButtonDownObservable.notifyObservers(buttonType);
  65764. }
  65765. if (newValue === 0) {
  65766. if (this._onbuttonup) {
  65767. this._onbuttonup(buttonType);
  65768. }
  65769. this.onButtonUpObservable.notifyObservers(buttonType);
  65770. }
  65771. }
  65772. return newValue;
  65773. };
  65774. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  65775. if (newValue !== currentValue) {
  65776. if (newValue === 1) {
  65777. if (this._ondpaddown) {
  65778. this._ondpaddown(buttonType);
  65779. }
  65780. this.onPadDownObservable.notifyObservers(buttonType);
  65781. }
  65782. if (newValue === 0) {
  65783. if (this._ondpadup) {
  65784. this._ondpadup(buttonType);
  65785. }
  65786. this.onPadUpObservable.notifyObservers(buttonType);
  65787. }
  65788. }
  65789. return newValue;
  65790. };
  65791. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  65792. get: function () {
  65793. return this._buttonA;
  65794. },
  65795. set: function (value) {
  65796. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  65797. },
  65798. enumerable: true,
  65799. configurable: true
  65800. });
  65801. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  65802. get: function () {
  65803. return this._buttonB;
  65804. },
  65805. set: function (value) {
  65806. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  65807. },
  65808. enumerable: true,
  65809. configurable: true
  65810. });
  65811. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  65812. get: function () {
  65813. return this._buttonX;
  65814. },
  65815. set: function (value) {
  65816. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  65817. },
  65818. enumerable: true,
  65819. configurable: true
  65820. });
  65821. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  65822. get: function () {
  65823. return this._buttonY;
  65824. },
  65825. set: function (value) {
  65826. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  65827. },
  65828. enumerable: true,
  65829. configurable: true
  65830. });
  65831. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  65832. get: function () {
  65833. return this._buttonStart;
  65834. },
  65835. set: function (value) {
  65836. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  65837. },
  65838. enumerable: true,
  65839. configurable: true
  65840. });
  65841. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  65842. get: function () {
  65843. return this._buttonBack;
  65844. },
  65845. set: function (value) {
  65846. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  65847. },
  65848. enumerable: true,
  65849. configurable: true
  65850. });
  65851. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  65852. get: function () {
  65853. return this._buttonLB;
  65854. },
  65855. set: function (value) {
  65856. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  65857. },
  65858. enumerable: true,
  65859. configurable: true
  65860. });
  65861. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  65862. get: function () {
  65863. return this._buttonRB;
  65864. },
  65865. set: function (value) {
  65866. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  65867. },
  65868. enumerable: true,
  65869. configurable: true
  65870. });
  65871. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  65872. get: function () {
  65873. return this._buttonLeftStick;
  65874. },
  65875. set: function (value) {
  65876. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  65877. },
  65878. enumerable: true,
  65879. configurable: true
  65880. });
  65881. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  65882. get: function () {
  65883. return this._buttonRightStick;
  65884. },
  65885. set: function (value) {
  65886. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  65887. },
  65888. enumerable: true,
  65889. configurable: true
  65890. });
  65891. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  65892. get: function () {
  65893. return this._dPadUp;
  65894. },
  65895. set: function (value) {
  65896. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  65897. },
  65898. enumerable: true,
  65899. configurable: true
  65900. });
  65901. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  65902. get: function () {
  65903. return this._dPadDown;
  65904. },
  65905. set: function (value) {
  65906. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  65907. },
  65908. enumerable: true,
  65909. configurable: true
  65910. });
  65911. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  65912. get: function () {
  65913. return this._dPadLeft;
  65914. },
  65915. set: function (value) {
  65916. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  65917. },
  65918. enumerable: true,
  65919. configurable: true
  65920. });
  65921. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  65922. get: function () {
  65923. return this._dPadRight;
  65924. },
  65925. set: function (value) {
  65926. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  65927. },
  65928. enumerable: true,
  65929. configurable: true
  65930. });
  65931. Xbox360Pad.prototype.update = function () {
  65932. _super.prototype.update.call(this);
  65933. if (this._isXboxOnePad) {
  65934. this.buttonA = this.browserGamepad.buttons[0].value;
  65935. this.buttonB = this.browserGamepad.buttons[1].value;
  65936. this.buttonX = this.browserGamepad.buttons[2].value;
  65937. this.buttonY = this.browserGamepad.buttons[3].value;
  65938. this.buttonLB = this.browserGamepad.buttons[4].value;
  65939. this.buttonRB = this.browserGamepad.buttons[5].value;
  65940. this.leftTrigger = this.browserGamepad.axes[2];
  65941. this.rightTrigger = this.browserGamepad.axes[5];
  65942. this.buttonBack = this.browserGamepad.buttons[9].value;
  65943. this.buttonStart = this.browserGamepad.buttons[8].value;
  65944. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  65945. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  65946. this.dPadUp = this.browserGamepad.buttons[11].value;
  65947. this.dPadDown = this.browserGamepad.buttons[12].value;
  65948. this.dPadLeft = this.browserGamepad.buttons[13].value;
  65949. this.dPadRight = this.browserGamepad.buttons[14].value;
  65950. }
  65951. else {
  65952. this.buttonA = this.browserGamepad.buttons[0].value;
  65953. this.buttonB = this.browserGamepad.buttons[1].value;
  65954. this.buttonX = this.browserGamepad.buttons[2].value;
  65955. this.buttonY = this.browserGamepad.buttons[3].value;
  65956. this.buttonLB = this.browserGamepad.buttons[4].value;
  65957. this.buttonRB = this.browserGamepad.buttons[5].value;
  65958. this.leftTrigger = this.browserGamepad.buttons[6].value;
  65959. this.rightTrigger = this.browserGamepad.buttons[7].value;
  65960. this.buttonBack = this.browserGamepad.buttons[8].value;
  65961. this.buttonStart = this.browserGamepad.buttons[9].value;
  65962. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  65963. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  65964. this.dPadUp = this.browserGamepad.buttons[12].value;
  65965. this.dPadDown = this.browserGamepad.buttons[13].value;
  65966. this.dPadLeft = this.browserGamepad.buttons[14].value;
  65967. this.dPadRight = this.browserGamepad.buttons[15].value;
  65968. }
  65969. };
  65970. Xbox360Pad.prototype.dispose = function () {
  65971. _super.prototype.dispose.call(this);
  65972. this.onButtonDownObservable.clear();
  65973. this.onButtonUpObservable.clear();
  65974. this.onPadDownObservable.clear();
  65975. this.onPadUpObservable.clear();
  65976. };
  65977. return Xbox360Pad;
  65978. }(BABYLON.Gamepad));
  65979. BABYLON.Xbox360Pad = Xbox360Pad;
  65980. })(BABYLON || (BABYLON = {}));
  65981. //# sourceMappingURL=babylon.xboxGamepad.js.map
  65982. var BABYLON;
  65983. (function (BABYLON) {
  65984. var PoseEnabledControllerType;
  65985. (function (PoseEnabledControllerType) {
  65986. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  65987. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  65988. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  65989. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  65990. /**
  65991. * Google Daydream
  65992. */
  65993. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  65994. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  65995. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  65996. var PoseEnabledControllerHelper = /** @class */ (function () {
  65997. function PoseEnabledControllerHelper() {
  65998. }
  65999. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  66000. // Oculus Touch
  66001. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  66002. return new BABYLON.OculusTouchController(vrGamepad);
  66003. }
  66004. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  66005. return new BABYLON.WindowsMotionController(vrGamepad);
  66006. }
  66007. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  66008. return new BABYLON.ViveController(vrGamepad);
  66009. }
  66010. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  66011. return new BABYLON.GearVRController(vrGamepad);
  66012. }
  66013. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  66014. return new BABYLON.DaydreamController(vrGamepad);
  66015. }
  66016. else {
  66017. return new BABYLON.GenericController(vrGamepad);
  66018. }
  66019. };
  66020. return PoseEnabledControllerHelper;
  66021. }());
  66022. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  66023. var PoseEnabledController = /** @class */ (function (_super) {
  66024. __extends(PoseEnabledController, _super);
  66025. function PoseEnabledController(browserGamepad) {
  66026. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  66027. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  66028. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  66029. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  66030. // Represents device position and rotation in babylon space
  66031. _this.devicePosition = BABYLON.Vector3.Zero();
  66032. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  66033. _this.deviceScaleFactor = 1;
  66034. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  66035. _this._deviceToWorld = BABYLON.Matrix.Identity();
  66036. /**
  66037. * Node to be used when casting a ray from the controller
  66038. */
  66039. _this._pointingPoseNode = null;
  66040. _this._workingMatrix = BABYLON.Matrix.Identity();
  66041. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  66042. _this.controllerType = PoseEnabledControllerType.GENERIC;
  66043. _this.position = BABYLON.Vector3.Zero();
  66044. _this.rotationQuaternion = new BABYLON.Quaternion();
  66045. _this._calculatedPosition = BABYLON.Vector3.Zero();
  66046. _this._calculatedRotation = new BABYLON.Quaternion();
  66047. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  66048. return _this;
  66049. }
  66050. PoseEnabledController.prototype.update = function () {
  66051. _super.prototype.update.call(this);
  66052. var pose = this.browserGamepad.pose;
  66053. this.updateFromDevice(pose);
  66054. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  66055. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  66056. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  66057. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  66058. if (this._mesh) {
  66059. this._mesh.position.copyFrom(this.devicePosition);
  66060. if (this._mesh.rotationQuaternion) {
  66061. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  66062. }
  66063. }
  66064. };
  66065. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  66066. if (poseData) {
  66067. this.rawPose = poseData;
  66068. if (poseData.position) {
  66069. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  66070. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  66071. this._deviceRoomPosition.z *= -1;
  66072. }
  66073. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  66074. this._calculatedPosition.addInPlace(this.position);
  66075. }
  66076. var pose = this.rawPose;
  66077. if (poseData.orientation && pose.orientation) {
  66078. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  66079. if (this._mesh) {
  66080. if (this._mesh.getScene().useRightHandedSystem) {
  66081. this._deviceRoomRotationQuaternion.z *= -1;
  66082. this._deviceRoomRotationQuaternion.w *= -1;
  66083. }
  66084. else {
  66085. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  66086. }
  66087. }
  66088. // if the camera is set, rotate to the camera's rotation
  66089. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  66090. }
  66091. }
  66092. };
  66093. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  66094. if (this._mesh) {
  66095. this._mesh.parent = null;
  66096. }
  66097. this._mesh = mesh;
  66098. if (this._poseControlledCamera) {
  66099. this._mesh.parent = this._poseControlledCamera;
  66100. }
  66101. if (!this._mesh.rotationQuaternion) {
  66102. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  66103. }
  66104. };
  66105. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  66106. this._poseControlledCamera = camera;
  66107. if (this._mesh) {
  66108. this._mesh.parent = this._poseControlledCamera;
  66109. }
  66110. };
  66111. PoseEnabledController.prototype.dispose = function () {
  66112. if (this._mesh) {
  66113. this._mesh.dispose();
  66114. }
  66115. this._mesh = null;
  66116. _super.prototype.dispose.call(this);
  66117. };
  66118. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  66119. get: function () {
  66120. return this._mesh;
  66121. },
  66122. enumerable: true,
  66123. configurable: true
  66124. });
  66125. PoseEnabledController.prototype.getForwardRay = function (length) {
  66126. if (length === void 0) { length = 100; }
  66127. if (!this.mesh) {
  66128. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  66129. }
  66130. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  66131. var origin = m.getTranslation();
  66132. var forward = new BABYLON.Vector3(0, 0, -1);
  66133. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  66134. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  66135. return new BABYLON.Ray(origin, direction, length);
  66136. };
  66137. /**
  66138. * Name of the child mesh that can be used to cast a ray from the controller
  66139. */
  66140. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  66141. return PoseEnabledController;
  66142. }(BABYLON.Gamepad));
  66143. BABYLON.PoseEnabledController = PoseEnabledController;
  66144. })(BABYLON || (BABYLON = {}));
  66145. //# sourceMappingURL=babylon.poseEnabledController.js.map
  66146. var BABYLON;
  66147. (function (BABYLON) {
  66148. var WebVRController = /** @class */ (function (_super) {
  66149. __extends(WebVRController, _super);
  66150. function WebVRController(vrGamepad) {
  66151. var _this = _super.call(this, vrGamepad) || this;
  66152. // Observables
  66153. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  66154. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  66155. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  66156. _this.onPadStateChangedObservable = new BABYLON.Observable();
  66157. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  66158. _this.pad = { x: 0, y: 0 };
  66159. // avoid GC, store state in a tmp object
  66160. _this._changes = {
  66161. pressChanged: false,
  66162. touchChanged: false,
  66163. valueChanged: false,
  66164. changed: false
  66165. };
  66166. _this._buttons = new Array(vrGamepad.buttons.length);
  66167. _this.hand = vrGamepad.hand;
  66168. return _this;
  66169. }
  66170. WebVRController.prototype.onButtonStateChange = function (callback) {
  66171. this._onButtonStateChange = callback;
  66172. };
  66173. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  66174. get: function () {
  66175. return this._defaultModel;
  66176. },
  66177. enumerable: true,
  66178. configurable: true
  66179. });
  66180. WebVRController.prototype.update = function () {
  66181. _super.prototype.update.call(this);
  66182. for (var index = 0; index < this._buttons.length; index++) {
  66183. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  66184. }
  66185. ;
  66186. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  66187. this.pad.x = this.leftStick.x;
  66188. this.pad.y = this.leftStick.y;
  66189. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  66190. }
  66191. };
  66192. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  66193. if (!newState) {
  66194. newState = {
  66195. pressed: false,
  66196. touched: false,
  66197. value: 0
  66198. };
  66199. }
  66200. if (!currentState) {
  66201. this._buttons[buttonIndex] = {
  66202. pressed: newState.pressed,
  66203. touched: newState.touched,
  66204. value: newState.value
  66205. };
  66206. return;
  66207. }
  66208. this._checkChanges(newState, currentState);
  66209. if (this._changes.changed) {
  66210. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  66211. this._handleButtonChange(buttonIndex, newState, this._changes);
  66212. }
  66213. this._buttons[buttonIndex].pressed = newState.pressed;
  66214. this._buttons[buttonIndex].touched = newState.touched;
  66215. // oculus triggers are never 0, thou not touched.
  66216. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  66217. };
  66218. WebVRController.prototype._checkChanges = function (newState, currentState) {
  66219. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  66220. this._changes.touchChanged = newState.touched !== currentState.touched;
  66221. this._changes.valueChanged = newState.value !== currentState.value;
  66222. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  66223. return this._changes;
  66224. };
  66225. WebVRController.prototype.dispose = function () {
  66226. _super.prototype.dispose.call(this);
  66227. this.onTriggerStateChangedObservable.clear();
  66228. this.onMainButtonStateChangedObservable.clear();
  66229. this.onSecondaryButtonStateChangedObservable.clear();
  66230. this.onPadStateChangedObservable.clear();
  66231. this.onPadValuesChangedObservable.clear();
  66232. };
  66233. return WebVRController;
  66234. }(BABYLON.PoseEnabledController));
  66235. BABYLON.WebVRController = WebVRController;
  66236. })(BABYLON || (BABYLON = {}));
  66237. //# sourceMappingURL=babylon.webVRController.js.map
  66238. var BABYLON;
  66239. (function (BABYLON) {
  66240. var OculusTouchController = /** @class */ (function (_super) {
  66241. __extends(OculusTouchController, _super);
  66242. function OculusTouchController(vrGamepad) {
  66243. var _this = _super.call(this, vrGamepad) || this;
  66244. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  66245. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  66246. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  66247. return _this;
  66248. }
  66249. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66250. var _this = this;
  66251. var meshName;
  66252. // Hand
  66253. if (this.hand === 'left') {
  66254. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  66255. }
  66256. else {
  66257. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  66258. }
  66259. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  66260. /*
  66261. Parent Mesh name: oculus_touch_left
  66262. - body
  66263. - trigger
  66264. - thumbstick
  66265. - grip
  66266. - button_y
  66267. - button_x
  66268. - button_enter
  66269. */
  66270. _this._defaultModel = newMeshes[1];
  66271. _this.attachToMesh(_this._defaultModel);
  66272. if (meshLoaded) {
  66273. meshLoaded(_this._defaultModel);
  66274. }
  66275. });
  66276. };
  66277. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  66278. // helper getters for left and right hand.
  66279. get: function () {
  66280. if (this.hand === 'right') {
  66281. return this.onMainButtonStateChangedObservable;
  66282. }
  66283. else {
  66284. throw new Error('No A button on left hand');
  66285. }
  66286. },
  66287. enumerable: true,
  66288. configurable: true
  66289. });
  66290. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  66291. get: function () {
  66292. if (this.hand === 'right') {
  66293. return this.onSecondaryButtonStateChangedObservable;
  66294. }
  66295. else {
  66296. throw new Error('No B button on left hand');
  66297. }
  66298. },
  66299. enumerable: true,
  66300. configurable: true
  66301. });
  66302. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  66303. get: function () {
  66304. if (this.hand === 'left') {
  66305. return this.onMainButtonStateChangedObservable;
  66306. }
  66307. else {
  66308. throw new Error('No X button on right hand');
  66309. }
  66310. },
  66311. enumerable: true,
  66312. configurable: true
  66313. });
  66314. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  66315. get: function () {
  66316. if (this.hand === 'left') {
  66317. return this.onSecondaryButtonStateChangedObservable;
  66318. }
  66319. else {
  66320. throw new Error('No Y button on right hand');
  66321. }
  66322. },
  66323. enumerable: true,
  66324. configurable: true
  66325. });
  66326. /*
  66327. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  66328. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  66329. 2) secondary trigger (same)
  66330. 3) A (right) X (left), touch, pressed = value
  66331. 4) B / Y
  66332. 5) thumb rest
  66333. */
  66334. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66335. var notifyObject = state; //{ state: state, changes: changes };
  66336. var triggerDirection = this.hand === 'right' ? -1 : 1;
  66337. switch (buttonIdx) {
  66338. case 0:
  66339. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  66340. return;
  66341. case 1:// index trigger
  66342. if (this._defaultModel) {
  66343. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  66344. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  66345. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  66346. }
  66347. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  66348. return;
  66349. case 2:// secondary trigger
  66350. if (this._defaultModel) {
  66351. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  66352. }
  66353. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  66354. return;
  66355. case 3:
  66356. if (this._defaultModel) {
  66357. if (notifyObject.pressed) {
  66358. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  66359. }
  66360. else {
  66361. (this._defaultModel.getChildren()[1]).position.y = 0;
  66362. }
  66363. }
  66364. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  66365. return;
  66366. case 4:
  66367. if (this._defaultModel) {
  66368. if (notifyObject.pressed) {
  66369. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  66370. }
  66371. else {
  66372. (this._defaultModel.getChildren()[2]).position.y = 0;
  66373. }
  66374. }
  66375. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  66376. return;
  66377. case 5:
  66378. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  66379. return;
  66380. }
  66381. };
  66382. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  66383. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  66384. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  66385. return OculusTouchController;
  66386. }(BABYLON.WebVRController));
  66387. BABYLON.OculusTouchController = OculusTouchController;
  66388. })(BABYLON || (BABYLON = {}));
  66389. //# sourceMappingURL=babylon.oculusTouchController.js.map
  66390. var BABYLON;
  66391. (function (BABYLON) {
  66392. var ViveController = /** @class */ (function (_super) {
  66393. __extends(ViveController, _super);
  66394. function ViveController(vrGamepad) {
  66395. var _this = _super.call(this, vrGamepad) || this;
  66396. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  66397. _this._invertLeftStickY = true;
  66398. return _this;
  66399. }
  66400. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66401. var _this = this;
  66402. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  66403. /*
  66404. Parent Mesh name: ViveWand
  66405. - body
  66406. - r_gripper
  66407. - l_gripper
  66408. - menu_button
  66409. - system_button
  66410. - trackpad
  66411. - trigger
  66412. - LED
  66413. */
  66414. _this._defaultModel = newMeshes[1];
  66415. _this.attachToMesh(_this._defaultModel);
  66416. if (meshLoaded) {
  66417. meshLoaded(_this._defaultModel);
  66418. }
  66419. });
  66420. };
  66421. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  66422. get: function () {
  66423. return this.onMainButtonStateChangedObservable;
  66424. },
  66425. enumerable: true,
  66426. configurable: true
  66427. });
  66428. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  66429. get: function () {
  66430. return this.onMainButtonStateChangedObservable;
  66431. },
  66432. enumerable: true,
  66433. configurable: true
  66434. });
  66435. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  66436. get: function () {
  66437. return this.onSecondaryButtonStateChangedObservable;
  66438. },
  66439. enumerable: true,
  66440. configurable: true
  66441. });
  66442. /**
  66443. * Vive mapping:
  66444. * 0: touchpad
  66445. * 1: trigger
  66446. * 2: left AND right buttons
  66447. * 3: menu button
  66448. */
  66449. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66450. var notifyObject = state; //{ state: state, changes: changes };
  66451. switch (buttonIdx) {
  66452. case 0:
  66453. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  66454. return;
  66455. case 1:// index trigger
  66456. if (this._defaultModel) {
  66457. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  66458. }
  66459. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  66460. return;
  66461. case 2:// left AND right button
  66462. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  66463. return;
  66464. case 3:
  66465. if (this._defaultModel) {
  66466. if (notifyObject.pressed) {
  66467. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  66468. }
  66469. else {
  66470. (this._defaultModel.getChildren()[2]).position.y = 0;
  66471. }
  66472. }
  66473. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  66474. return;
  66475. }
  66476. };
  66477. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  66478. ViveController.MODEL_FILENAME = 'wand.babylon';
  66479. return ViveController;
  66480. }(BABYLON.WebVRController));
  66481. BABYLON.ViveController = ViveController;
  66482. })(BABYLON || (BABYLON = {}));
  66483. //# sourceMappingURL=babylon.viveController.js.map
  66484. var BABYLON;
  66485. (function (BABYLON) {
  66486. var GenericController = /** @class */ (function (_super) {
  66487. __extends(GenericController, _super);
  66488. function GenericController(vrGamepad) {
  66489. return _super.call(this, vrGamepad) || this;
  66490. }
  66491. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66492. var _this = this;
  66493. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  66494. _this._defaultModel = newMeshes[1];
  66495. _this.attachToMesh(_this._defaultModel);
  66496. if (meshLoaded) {
  66497. meshLoaded(_this._defaultModel);
  66498. }
  66499. });
  66500. };
  66501. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66502. console.log("Button id: " + buttonIdx + "state: ");
  66503. console.dir(state);
  66504. };
  66505. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  66506. GenericController.MODEL_FILENAME = 'generic.babylon';
  66507. return GenericController;
  66508. }(BABYLON.WebVRController));
  66509. BABYLON.GenericController = GenericController;
  66510. })(BABYLON || (BABYLON = {}));
  66511. //# sourceMappingURL=babylon.genericController.js.map
  66512. var BABYLON;
  66513. (function (BABYLON) {
  66514. var LoadedMeshInfo = /** @class */ (function () {
  66515. function LoadedMeshInfo() {
  66516. this.buttonMeshes = {};
  66517. this.axisMeshes = {};
  66518. }
  66519. return LoadedMeshInfo;
  66520. }());
  66521. var WindowsMotionController = /** @class */ (function (_super) {
  66522. __extends(WindowsMotionController, _super);
  66523. function WindowsMotionController(vrGamepad) {
  66524. var _this = _super.call(this, vrGamepad) || this;
  66525. _this._mapping = {
  66526. // Semantic button names
  66527. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  66528. // A mapping of the button name to glTF model node name
  66529. // that should be transformed by button value.
  66530. buttonMeshNames: {
  66531. 'trigger': 'SELECT',
  66532. 'menu': 'MENU',
  66533. 'grip': 'GRASP',
  66534. 'thumbstick': 'THUMBSTICK_PRESS',
  66535. 'trackpad': 'TOUCHPAD_PRESS'
  66536. },
  66537. // This mapping is used to translate from the Motion Controller to Babylon semantics
  66538. buttonObservableNames: {
  66539. 'trigger': 'onTriggerStateChangedObservable',
  66540. 'menu': 'onSecondaryButtonStateChangedObservable',
  66541. 'grip': 'onMainButtonStateChangedObservable',
  66542. 'thumbstick': 'onPadStateChangedObservable',
  66543. 'trackpad': 'onTrackpadChangedObservable'
  66544. },
  66545. // A mapping of the axis name to glTF model node name
  66546. // that should be transformed by axis value.
  66547. // This array mirrors the browserGamepad.axes array, such that
  66548. // the mesh corresponding to axis 0 is in this array index 0.
  66549. axisMeshNames: [
  66550. 'THUMBSTICK_X',
  66551. 'THUMBSTICK_Y',
  66552. 'TOUCHPAD_TOUCH_X',
  66553. 'TOUCHPAD_TOUCH_Y'
  66554. ],
  66555. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  66556. };
  66557. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  66558. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  66559. _this.trackpad = { x: 0, y: 0 };
  66560. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  66561. _this._loadedMeshInfo = null;
  66562. return _this;
  66563. }
  66564. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  66565. get: function () {
  66566. return this.onTriggerStateChangedObservable;
  66567. },
  66568. enumerable: true,
  66569. configurable: true
  66570. });
  66571. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  66572. get: function () {
  66573. return this.onSecondaryButtonStateChangedObservable;
  66574. },
  66575. enumerable: true,
  66576. configurable: true
  66577. });
  66578. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  66579. get: function () {
  66580. return this.onMainButtonStateChangedObservable;
  66581. },
  66582. enumerable: true,
  66583. configurable: true
  66584. });
  66585. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  66586. get: function () {
  66587. return this.onPadStateChangedObservable;
  66588. },
  66589. enumerable: true,
  66590. configurable: true
  66591. });
  66592. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  66593. get: function () {
  66594. return this.onTrackpadChangedObservable;
  66595. },
  66596. enumerable: true,
  66597. configurable: true
  66598. });
  66599. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  66600. get: function () {
  66601. return this.onTrackpadValuesChangedObservable;
  66602. },
  66603. enumerable: true,
  66604. configurable: true
  66605. });
  66606. /**
  66607. * Called once per frame by the engine.
  66608. */
  66609. WindowsMotionController.prototype.update = function () {
  66610. _super.prototype.update.call(this);
  66611. if (this.browserGamepad.axes) {
  66612. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  66613. this.trackpad.x = this.browserGamepad["axes"][2];
  66614. this.trackpad.y = this.browserGamepad["axes"][3];
  66615. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  66616. }
  66617. // Only need to animate axes if there is a loaded mesh
  66618. if (this._loadedMeshInfo) {
  66619. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  66620. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  66621. }
  66622. }
  66623. }
  66624. };
  66625. /**
  66626. * Called once for each button that changed state since the last frame
  66627. * @param buttonIdx Which button index changed
  66628. * @param state New state of the button
  66629. * @param changes Which properties on the state changed since last frame
  66630. */
  66631. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66632. var buttonName = this._mapping.buttons[buttonIdx];
  66633. if (!buttonName) {
  66634. return;
  66635. }
  66636. // Only emit events for buttons that we know how to map from index to name
  66637. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  66638. if (observable) {
  66639. observable.notifyObservers(state);
  66640. }
  66641. this.lerpButtonTransform(buttonName, state.value);
  66642. };
  66643. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  66644. // If there is no loaded mesh, there is nothing to transform.
  66645. if (!this._loadedMeshInfo) {
  66646. return;
  66647. }
  66648. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  66649. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  66650. return;
  66651. }
  66652. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  66653. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  66654. };
  66655. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  66656. if (!this._loadedMeshInfo) {
  66657. return;
  66658. }
  66659. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  66660. if (!meshInfo) {
  66661. return;
  66662. }
  66663. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  66664. return;
  66665. }
  66666. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  66667. var lerpValue = axisValue * 0.5 + 0.5;
  66668. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  66669. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  66670. };
  66671. /**
  66672. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  66673. * @param scene scene in which to add meshes
  66674. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  66675. */
  66676. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  66677. var _this = this;
  66678. if (forceDefault === void 0) { forceDefault = false; }
  66679. var path;
  66680. var filename;
  66681. // Checking if GLB loader is present
  66682. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  66683. // Determine the device specific folder based on the ID suffix
  66684. var device = 'default';
  66685. if (this.id && !forceDefault) {
  66686. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  66687. device = ((match && match[0]) || device);
  66688. }
  66689. // Hand
  66690. if (this.hand === 'left') {
  66691. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  66692. }
  66693. else {
  66694. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  66695. }
  66696. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  66697. }
  66698. else {
  66699. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  66700. path = BABYLON.GenericController.MODEL_BASE_URL;
  66701. filename = BABYLON.GenericController.MODEL_FILENAME;
  66702. }
  66703. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  66704. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  66705. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  66706. if (!_this._loadedMeshInfo) {
  66707. return;
  66708. }
  66709. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  66710. _this.attachToMesh(_this._defaultModel);
  66711. if (meshLoaded) {
  66712. meshLoaded(_this._defaultModel);
  66713. }
  66714. }, null, function (scene, message) {
  66715. BABYLON.Tools.Log(message);
  66716. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  66717. if (!forceDefault) {
  66718. _this.initControllerMesh(scene, meshLoaded, true);
  66719. }
  66720. });
  66721. };
  66722. /**
  66723. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  66724. * can be transformed by button presses and axes values, based on this._mapping.
  66725. *
  66726. * @param scene scene in which the meshes exist
  66727. * @param meshes list of meshes that make up the controller model to process
  66728. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  66729. */
  66730. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  66731. var loadedMeshInfo = null;
  66732. // Create a new mesh to contain the glTF hierarchy
  66733. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  66734. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  66735. var childMesh = null;
  66736. for (var i = 0; i < meshes.length; i++) {
  66737. var mesh = meshes[i];
  66738. if (!mesh.parent) {
  66739. // Exclude controller meshes from picking results
  66740. mesh.isPickable = false;
  66741. // Handle root node, attach to the new parentMesh
  66742. childMesh = mesh;
  66743. break;
  66744. }
  66745. }
  66746. if (childMesh) {
  66747. childMesh.setParent(parentMesh);
  66748. // Create our mesh info. Note that this method will always return non-null.
  66749. loadedMeshInfo = this.createMeshInfo(parentMesh);
  66750. }
  66751. else {
  66752. BABYLON.Tools.Warn('Could not find root node in model file.');
  66753. }
  66754. return loadedMeshInfo;
  66755. };
  66756. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  66757. var loadedMeshInfo = new LoadedMeshInfo();
  66758. var i;
  66759. loadedMeshInfo.rootNode = rootNode;
  66760. // Reset the caches
  66761. loadedMeshInfo.buttonMeshes = {};
  66762. loadedMeshInfo.axisMeshes = {};
  66763. // Button Meshes
  66764. for (i = 0; i < this._mapping.buttons.length; i++) {
  66765. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  66766. if (!buttonMeshName) {
  66767. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  66768. continue;
  66769. }
  66770. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  66771. if (!buttonMesh) {
  66772. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  66773. continue;
  66774. }
  66775. var buttonMeshInfo = {
  66776. index: i,
  66777. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  66778. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  66779. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  66780. };
  66781. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  66782. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  66783. }
  66784. else {
  66785. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  66786. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  66787. '(VALUE: ' + !!buttonMeshInfo.value +
  66788. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  66789. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  66790. ')');
  66791. }
  66792. }
  66793. // Axis Meshes
  66794. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  66795. var axisMeshName = this._mapping.axisMeshNames[i];
  66796. if (!axisMeshName) {
  66797. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  66798. continue;
  66799. }
  66800. var axisMesh = getChildByName(rootNode, axisMeshName);
  66801. if (!axisMesh) {
  66802. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  66803. continue;
  66804. }
  66805. var axisMeshInfo = {
  66806. index: i,
  66807. value: getImmediateChildByName(axisMesh, 'VALUE'),
  66808. min: getImmediateChildByName(axisMesh, 'MIN'),
  66809. max: getImmediateChildByName(axisMesh, 'MAX')
  66810. };
  66811. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  66812. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  66813. }
  66814. else {
  66815. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  66816. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  66817. '(VALUE: ' + !!axisMeshInfo.value +
  66818. ', MIN: ' + !!axisMeshInfo.min +
  66819. ', MAX:' + !!axisMeshInfo.max +
  66820. ')');
  66821. }
  66822. }
  66823. // Pointing Ray
  66824. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  66825. if (!loadedMeshInfo.pointingPoseNode) {
  66826. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  66827. }
  66828. return loadedMeshInfo;
  66829. // Look through all children recursively. This will return null if no mesh exists with the given name.
  66830. function getChildByName(node, name) {
  66831. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  66832. }
  66833. // Look through only immediate children. This will return null if no mesh exists with the given name.
  66834. function getImmediateChildByName(node, name) {
  66835. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  66836. }
  66837. };
  66838. WindowsMotionController.prototype.getForwardRay = function (length) {
  66839. if (length === void 0) { length = 100; }
  66840. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  66841. return _super.prototype.getForwardRay.call(this, length);
  66842. }
  66843. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  66844. var origin = m.getTranslation();
  66845. var forward = new BABYLON.Vector3(0, 0, -1);
  66846. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  66847. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  66848. return new BABYLON.Ray(origin, direction, length);
  66849. };
  66850. WindowsMotionController.prototype.dispose = function () {
  66851. _super.prototype.dispose.call(this);
  66852. this.onTrackpadChangedObservable.clear();
  66853. };
  66854. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  66855. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  66856. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  66857. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  66858. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  66859. return WindowsMotionController;
  66860. }(BABYLON.WebVRController));
  66861. BABYLON.WindowsMotionController = WindowsMotionController;
  66862. })(BABYLON || (BABYLON = {}));
  66863. //# sourceMappingURL=babylon.windowsMotionController.js.map
  66864. var BABYLON;
  66865. (function (BABYLON) {
  66866. var GearVRController = /** @class */ (function (_super) {
  66867. __extends(GearVRController, _super);
  66868. function GearVRController(vrGamepad) {
  66869. var _this = _super.call(this, vrGamepad) || this;
  66870. _this._buttonIndexToObservableNameMap = [
  66871. 'onTrackpadChangedObservable',
  66872. 'onTriggerStateChangedObservable' // Trigger
  66873. ];
  66874. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  66875. return _this;
  66876. }
  66877. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66878. var _this = this;
  66879. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  66880. _this._defaultModel = newMeshes[1];
  66881. _this.attachToMesh(_this._defaultModel);
  66882. if (meshLoaded) {
  66883. meshLoaded(_this._defaultModel);
  66884. }
  66885. });
  66886. };
  66887. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66888. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  66889. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  66890. // Only emit events for buttons that we know how to map from index to observable
  66891. var observable = this[observableName];
  66892. if (observable) {
  66893. observable.notifyObservers(state);
  66894. }
  66895. }
  66896. };
  66897. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  66898. GearVRController.MODEL_FILENAME = 'generic.babylon';
  66899. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  66900. return GearVRController;
  66901. }(BABYLON.WebVRController));
  66902. BABYLON.GearVRController = GearVRController;
  66903. })(BABYLON || (BABYLON = {}));
  66904. //# sourceMappingURL=babylon.gearVRController.js.map
  66905. var BABYLON;
  66906. (function (BABYLON) {
  66907. /**
  66908. * Google Daydream controller
  66909. */
  66910. var DaydreamController = /** @class */ (function (_super) {
  66911. __extends(DaydreamController, _super);
  66912. function DaydreamController(vrGamepad) {
  66913. var _this = _super.call(this, vrGamepad) || this;
  66914. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  66915. return _this;
  66916. }
  66917. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66918. var _this = this;
  66919. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  66920. _this._defaultModel = newMeshes[1];
  66921. _this.attachToMesh(_this._defaultModel);
  66922. if (meshLoaded) {
  66923. meshLoaded(_this._defaultModel);
  66924. }
  66925. });
  66926. };
  66927. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66928. // Daydream controller only has 1 GamepadButton (on the trackpad).
  66929. if (buttonIdx === 0) {
  66930. var observable = this.onTriggerStateChangedObservable;
  66931. if (observable) {
  66932. observable.notifyObservers(state);
  66933. }
  66934. }
  66935. else {
  66936. // If the app or home buttons are ever made available
  66937. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  66938. }
  66939. };
  66940. /**
  66941. * Base Url for the controller model.
  66942. */
  66943. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  66944. /**
  66945. * File name for the controller model.
  66946. */
  66947. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  66948. /**
  66949. * Gamepad Id prefix used to identify Daydream Controller.
  66950. */
  66951. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  66952. return DaydreamController;
  66953. }(BABYLON.WebVRController));
  66954. BABYLON.DaydreamController = DaydreamController;
  66955. })(BABYLON || (BABYLON = {}));
  66956. //# sourceMappingURL=babylon.daydreamController.js.map
  66957. var BABYLON;
  66958. (function (BABYLON) {
  66959. var FollowCamera = /** @class */ (function (_super) {
  66960. __extends(FollowCamera, _super);
  66961. function FollowCamera(name, position, scene, lockedTarget) {
  66962. if (lockedTarget === void 0) { lockedTarget = null; }
  66963. var _this = _super.call(this, name, position, scene) || this;
  66964. _this.radius = 12;
  66965. _this.rotationOffset = 0;
  66966. _this.heightOffset = 4;
  66967. _this.cameraAcceleration = 0.05;
  66968. _this.maxCameraSpeed = 20;
  66969. _this.lockedTarget = lockedTarget;
  66970. return _this;
  66971. }
  66972. FollowCamera.prototype.getRadians = function (degrees) {
  66973. return degrees * Math.PI / 180;
  66974. };
  66975. FollowCamera.prototype.follow = function (cameraTarget) {
  66976. if (!cameraTarget)
  66977. return;
  66978. var yRotation;
  66979. if (cameraTarget.rotationQuaternion) {
  66980. var rotMatrix = new BABYLON.Matrix();
  66981. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  66982. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  66983. }
  66984. else {
  66985. yRotation = cameraTarget.rotation.y;
  66986. }
  66987. var radians = this.getRadians(this.rotationOffset) + yRotation;
  66988. var targetPosition = cameraTarget.getAbsolutePosition();
  66989. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  66990. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  66991. var dx = targetX - this.position.x;
  66992. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  66993. var dz = (targetZ) - this.position.z;
  66994. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  66995. var vy = dy * this.cameraAcceleration;
  66996. var vz = dz * this.cameraAcceleration * 2;
  66997. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  66998. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  66999. }
  67000. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  67001. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67002. }
  67003. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  67004. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67005. }
  67006. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  67007. this.setTarget(targetPosition);
  67008. };
  67009. FollowCamera.prototype._checkInputs = function () {
  67010. _super.prototype._checkInputs.call(this);
  67011. if (this.lockedTarget) {
  67012. this.follow(this.lockedTarget);
  67013. }
  67014. };
  67015. FollowCamera.prototype.getClassName = function () {
  67016. return "FollowCamera";
  67017. };
  67018. __decorate([
  67019. BABYLON.serialize()
  67020. ], FollowCamera.prototype, "radius", void 0);
  67021. __decorate([
  67022. BABYLON.serialize()
  67023. ], FollowCamera.prototype, "rotationOffset", void 0);
  67024. __decorate([
  67025. BABYLON.serialize()
  67026. ], FollowCamera.prototype, "heightOffset", void 0);
  67027. __decorate([
  67028. BABYLON.serialize()
  67029. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  67030. __decorate([
  67031. BABYLON.serialize()
  67032. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  67033. __decorate([
  67034. BABYLON.serializeAsMeshReference("lockedTargetId")
  67035. ], FollowCamera.prototype, "lockedTarget", void 0);
  67036. return FollowCamera;
  67037. }(BABYLON.TargetCamera));
  67038. BABYLON.FollowCamera = FollowCamera;
  67039. var ArcFollowCamera = /** @class */ (function (_super) {
  67040. __extends(ArcFollowCamera, _super);
  67041. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  67042. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  67043. _this.alpha = alpha;
  67044. _this.beta = beta;
  67045. _this.radius = radius;
  67046. _this.target = target;
  67047. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  67048. _this.follow();
  67049. return _this;
  67050. }
  67051. ArcFollowCamera.prototype.follow = function () {
  67052. if (!this.target) {
  67053. return;
  67054. }
  67055. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  67056. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  67057. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  67058. var targetPosition = this.target.getAbsolutePosition();
  67059. this.position = targetPosition.add(this._cartesianCoordinates);
  67060. this.setTarget(targetPosition);
  67061. };
  67062. ArcFollowCamera.prototype._checkInputs = function () {
  67063. _super.prototype._checkInputs.call(this);
  67064. this.follow();
  67065. };
  67066. ArcFollowCamera.prototype.getClassName = function () {
  67067. return "ArcFollowCamera";
  67068. };
  67069. return ArcFollowCamera;
  67070. }(BABYLON.TargetCamera));
  67071. BABYLON.ArcFollowCamera = ArcFollowCamera;
  67072. })(BABYLON || (BABYLON = {}));
  67073. //# sourceMappingURL=babylon.followCamera.js.map
  67074. var BABYLON;
  67075. (function (BABYLON) {
  67076. // We're mainly based on the logic defined into the FreeCamera code
  67077. var UniversalCamera = /** @class */ (function (_super) {
  67078. __extends(UniversalCamera, _super);
  67079. //-- end properties for backward compatibility for inputs
  67080. function UniversalCamera(name, position, scene) {
  67081. var _this = _super.call(this, name, position, scene) || this;
  67082. _this.inputs.addGamepad();
  67083. return _this;
  67084. }
  67085. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  67086. //-- Begin properties for backward compatibility for inputs
  67087. get: function () {
  67088. var gamepad = this.inputs.attached["gamepad"];
  67089. if (gamepad)
  67090. return gamepad.gamepadAngularSensibility;
  67091. return 0;
  67092. },
  67093. set: function (value) {
  67094. var gamepad = this.inputs.attached["gamepad"];
  67095. if (gamepad)
  67096. gamepad.gamepadAngularSensibility = value;
  67097. },
  67098. enumerable: true,
  67099. configurable: true
  67100. });
  67101. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  67102. get: function () {
  67103. var gamepad = this.inputs.attached["gamepad"];
  67104. if (gamepad)
  67105. return gamepad.gamepadMoveSensibility;
  67106. return 0;
  67107. },
  67108. set: function (value) {
  67109. var gamepad = this.inputs.attached["gamepad"];
  67110. if (gamepad)
  67111. gamepad.gamepadMoveSensibility = value;
  67112. },
  67113. enumerable: true,
  67114. configurable: true
  67115. });
  67116. UniversalCamera.prototype.getClassName = function () {
  67117. return "UniversalCamera";
  67118. };
  67119. return UniversalCamera;
  67120. }(BABYLON.TouchCamera));
  67121. BABYLON.UniversalCamera = UniversalCamera;
  67122. })(BABYLON || (BABYLON = {}));
  67123. //# sourceMappingURL=babylon.universalCamera.js.map
  67124. var BABYLON;
  67125. (function (BABYLON) {
  67126. // We're mainly based on the logic defined into the FreeCamera code
  67127. var GamepadCamera = /** @class */ (function (_super) {
  67128. __extends(GamepadCamera, _super);
  67129. //-- end properties for backward compatibility for inputs
  67130. function GamepadCamera(name, position, scene) {
  67131. return _super.call(this, name, position, scene) || this;
  67132. }
  67133. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  67134. //-- Begin properties for backward compatibility for inputs
  67135. get: function () {
  67136. var gamepad = this.inputs.attached["gamepad"];
  67137. if (gamepad)
  67138. return gamepad.gamepadAngularSensibility;
  67139. return 0;
  67140. },
  67141. set: function (value) {
  67142. var gamepad = this.inputs.attached["gamepad"];
  67143. if (gamepad)
  67144. gamepad.gamepadAngularSensibility = value;
  67145. },
  67146. enumerable: true,
  67147. configurable: true
  67148. });
  67149. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  67150. get: function () {
  67151. var gamepad = this.inputs.attached["gamepad"];
  67152. if (gamepad)
  67153. return gamepad.gamepadMoveSensibility;
  67154. return 0;
  67155. },
  67156. set: function (value) {
  67157. var gamepad = this.inputs.attached["gamepad"];
  67158. if (gamepad)
  67159. gamepad.gamepadMoveSensibility = value;
  67160. },
  67161. enumerable: true,
  67162. configurable: true
  67163. });
  67164. GamepadCamera.prototype.getClassName = function () {
  67165. return "GamepadCamera";
  67166. };
  67167. return GamepadCamera;
  67168. }(BABYLON.UniversalCamera));
  67169. BABYLON.GamepadCamera = GamepadCamera;
  67170. })(BABYLON || (BABYLON = {}));
  67171. //# sourceMappingURL=babylon.gamepadCamera.js.map
  67172. var BABYLON;
  67173. (function (BABYLON) {
  67174. var PostProcessRenderPipelineManager = /** @class */ (function () {
  67175. function PostProcessRenderPipelineManager() {
  67176. this._renderPipelines = {};
  67177. }
  67178. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  67179. this._renderPipelines[renderPipeline._name] = renderPipeline;
  67180. };
  67181. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  67182. if (unique === void 0) { unique = false; }
  67183. var renderPipeline = this._renderPipelines[renderPipelineName];
  67184. if (!renderPipeline) {
  67185. return;
  67186. }
  67187. renderPipeline._attachCameras(cameras, unique);
  67188. };
  67189. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  67190. var renderPipeline = this._renderPipelines[renderPipelineName];
  67191. if (!renderPipeline) {
  67192. return;
  67193. }
  67194. renderPipeline._detachCameras(cameras);
  67195. };
  67196. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  67197. var renderPipeline = this._renderPipelines[renderPipelineName];
  67198. if (!renderPipeline) {
  67199. return;
  67200. }
  67201. renderPipeline._enableEffect(renderEffectName, cameras);
  67202. };
  67203. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  67204. var renderPipeline = this._renderPipelines[renderPipelineName];
  67205. if (!renderPipeline) {
  67206. return;
  67207. }
  67208. renderPipeline._disableEffect(renderEffectName, cameras);
  67209. };
  67210. PostProcessRenderPipelineManager.prototype.update = function () {
  67211. for (var renderPipelineName in this._renderPipelines) {
  67212. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67213. var pipeline = this._renderPipelines[renderPipelineName];
  67214. if (!pipeline.isSupported) {
  67215. pipeline.dispose();
  67216. delete this._renderPipelines[renderPipelineName];
  67217. }
  67218. else {
  67219. pipeline._update();
  67220. }
  67221. }
  67222. }
  67223. };
  67224. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  67225. for (var renderPipelineName in this._renderPipelines) {
  67226. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67227. var pipeline = this._renderPipelines[renderPipelineName];
  67228. pipeline._rebuild();
  67229. }
  67230. }
  67231. };
  67232. PostProcessRenderPipelineManager.prototype.dispose = function () {
  67233. for (var renderPipelineName in this._renderPipelines) {
  67234. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67235. var pipeline = this._renderPipelines[renderPipelineName];
  67236. pipeline.dispose();
  67237. }
  67238. }
  67239. };
  67240. return PostProcessRenderPipelineManager;
  67241. }());
  67242. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  67243. })(BABYLON || (BABYLON = {}));
  67244. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  67245. var BABYLON;
  67246. (function (BABYLON) {
  67247. /**
  67248. * This represents a set of one or more post processes in Babylon.
  67249. * A post process can be used to apply a shader to a texture after it is rendered.
  67250. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  67251. */
  67252. var PostProcessRenderEffect = /** @class */ (function () {
  67253. /**
  67254. * Instantiates a post process render effect.
  67255. * A post process can be used to apply a shader to a texture after it is rendered.
  67256. * @param engine The engine the effect is tied to
  67257. * @param name The name of the effect
  67258. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  67259. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  67260. */
  67261. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  67262. this._name = name;
  67263. this._singleInstance = singleInstance || true;
  67264. this._getPostProcesses = getPostProcesses;
  67265. this._cameras = {};
  67266. this._indicesForCamera = {};
  67267. this._postProcesses = {};
  67268. }
  67269. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  67270. /**
  67271. * Checks if all the post processes in the effect are supported.
  67272. */
  67273. get: function () {
  67274. for (var index in this._postProcesses) {
  67275. for (var ppIndex in this._postProcesses[index]) {
  67276. if (!this._postProcesses[index][ppIndex].isSupported) {
  67277. return false;
  67278. }
  67279. }
  67280. }
  67281. return true;
  67282. },
  67283. enumerable: true,
  67284. configurable: true
  67285. });
  67286. /**
  67287. * Updates the current state of the effect
  67288. */
  67289. PostProcessRenderEffect.prototype._update = function () {
  67290. };
  67291. /**
  67292. * Attaches the effect on cameras
  67293. * @param cameras The camera to attach to.
  67294. */
  67295. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  67296. var _this = this;
  67297. var cameraKey;
  67298. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67299. if (!cams) {
  67300. return;
  67301. }
  67302. for (var i = 0; i < cams.length; i++) {
  67303. var camera = cams[i];
  67304. var cameraName = camera.name;
  67305. if (this._singleInstance) {
  67306. cameraKey = 0;
  67307. }
  67308. else {
  67309. cameraKey = cameraName;
  67310. }
  67311. if (!this._postProcesses[cameraKey]) {
  67312. var postProcess = this._getPostProcesses();
  67313. if (postProcess) {
  67314. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  67315. }
  67316. }
  67317. if (!this._indicesForCamera[cameraName]) {
  67318. this._indicesForCamera[cameraName] = [];
  67319. }
  67320. this._postProcesses[cameraKey].forEach(function (postProcess) {
  67321. var index = camera.attachPostProcess(postProcess);
  67322. _this._indicesForCamera[cameraName].push(index);
  67323. });
  67324. if (!this._cameras[cameraName]) {
  67325. this._cameras[cameraName] = camera;
  67326. }
  67327. }
  67328. };
  67329. /**
  67330. * Detatches the effect on cameras
  67331. * @param cameras The camera to detatch from.
  67332. */
  67333. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  67334. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67335. if (!cams) {
  67336. return;
  67337. }
  67338. for (var i = 0; i < cams.length; i++) {
  67339. var camera = cams[i];
  67340. var cameraName = camera.name;
  67341. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67342. camera.detachPostProcess(postProcess);
  67343. });
  67344. if (this._cameras[cameraName]) {
  67345. //this._indicesForCamera.splice(index, 1);
  67346. this._cameras[cameraName] = null;
  67347. }
  67348. }
  67349. };
  67350. /**
  67351. * Enables the effect on given cameras
  67352. * @param cameras The camera to enable.
  67353. */
  67354. PostProcessRenderEffect.prototype._enable = function (cameras) {
  67355. var _this = this;
  67356. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67357. if (!cams) {
  67358. return;
  67359. }
  67360. for (var i = 0; i < cams.length; i++) {
  67361. var camera = cams[i];
  67362. var cameraName = camera.name;
  67363. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  67364. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  67365. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67366. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  67367. });
  67368. }
  67369. }
  67370. }
  67371. };
  67372. /**
  67373. * Disables the effect on the given cameras
  67374. * @param cameras The camera to disable.
  67375. */
  67376. PostProcessRenderEffect.prototype._disable = function (cameras) {
  67377. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67378. if (!cams) {
  67379. return;
  67380. }
  67381. for (var i = 0; i < cams.length; i++) {
  67382. var camera = cams[i];
  67383. var cameraName = camera.name;
  67384. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67385. camera.detachPostProcess(postProcess);
  67386. });
  67387. }
  67388. };
  67389. /**
  67390. * Gets a list of the post processes contained in the effect.
  67391. * @param camera The camera to get the post processes on.
  67392. * @returns The list of the post processes in the effect.
  67393. */
  67394. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  67395. if (this._singleInstance) {
  67396. return this._postProcesses[0];
  67397. }
  67398. else {
  67399. if (!camera) {
  67400. return null;
  67401. }
  67402. return this._postProcesses[camera.name];
  67403. }
  67404. };
  67405. return PostProcessRenderEffect;
  67406. }());
  67407. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  67408. })(BABYLON || (BABYLON = {}));
  67409. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  67410. var BABYLON;
  67411. (function (BABYLON) {
  67412. var PostProcessRenderPipeline = /** @class */ (function () {
  67413. function PostProcessRenderPipeline(engine, name) {
  67414. this.engine = engine;
  67415. this._name = name;
  67416. this._renderEffects = {};
  67417. this._renderEffectsForIsolatedPass = new Array();
  67418. this._cameras = [];
  67419. }
  67420. PostProcessRenderPipeline.prototype.getClassName = function () {
  67421. return "PostProcessRenderPipeline";
  67422. };
  67423. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  67424. get: function () {
  67425. for (var renderEffectName in this._renderEffects) {
  67426. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67427. if (!this._renderEffects[renderEffectName].isSupported) {
  67428. return false;
  67429. }
  67430. }
  67431. }
  67432. return true;
  67433. },
  67434. enumerable: true,
  67435. configurable: true
  67436. });
  67437. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  67438. this._renderEffects[renderEffect._name] = renderEffect;
  67439. };
  67440. // private
  67441. PostProcessRenderPipeline.prototype._rebuild = function () {
  67442. };
  67443. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  67444. var renderEffects = this._renderEffects[renderEffectName];
  67445. if (!renderEffects) {
  67446. return;
  67447. }
  67448. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  67449. };
  67450. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  67451. var renderEffects = this._renderEffects[renderEffectName];
  67452. if (!renderEffects) {
  67453. return;
  67454. }
  67455. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  67456. };
  67457. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  67458. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67459. if (!cams) {
  67460. return;
  67461. }
  67462. var indicesToDelete = [];
  67463. var i;
  67464. for (i = 0; i < cams.length; i++) {
  67465. var camera = cams[i];
  67466. var cameraName = camera.name;
  67467. if (this._cameras.indexOf(camera) === -1) {
  67468. this._cameras[cameraName] = camera;
  67469. }
  67470. else if (unique) {
  67471. indicesToDelete.push(i);
  67472. }
  67473. }
  67474. for (i = 0; i < indicesToDelete.length; i++) {
  67475. cameras.splice(indicesToDelete[i], 1);
  67476. }
  67477. for (var renderEffectName in this._renderEffects) {
  67478. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67479. this._renderEffects[renderEffectName]._attachCameras(cams);
  67480. }
  67481. }
  67482. };
  67483. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  67484. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67485. if (!cams) {
  67486. return;
  67487. }
  67488. for (var renderEffectName in this._renderEffects) {
  67489. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67490. this._renderEffects[renderEffectName]._detachCameras(cams);
  67491. }
  67492. }
  67493. for (var i = 0; i < cams.length; i++) {
  67494. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  67495. }
  67496. };
  67497. PostProcessRenderPipeline.prototype._update = function () {
  67498. for (var renderEffectName in this._renderEffects) {
  67499. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67500. this._renderEffects[renderEffectName]._update();
  67501. }
  67502. }
  67503. for (var i = 0; i < this._cameras.length; i++) {
  67504. var cameraName = this._cameras[i].name;
  67505. if (this._renderEffectsForIsolatedPass[cameraName]) {
  67506. this._renderEffectsForIsolatedPass[cameraName]._update();
  67507. }
  67508. }
  67509. };
  67510. PostProcessRenderPipeline.prototype._reset = function () {
  67511. this._renderEffects = {};
  67512. this._renderEffectsForIsolatedPass = new Array();
  67513. };
  67514. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function () {
  67515. // 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)
  67516. var effectKeys = Object.keys(this._renderEffects);
  67517. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  67518. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  67519. if (postProcesses) {
  67520. postProcesses[0].samples = 4;
  67521. return true;
  67522. }
  67523. }
  67524. return false;
  67525. };
  67526. PostProcessRenderPipeline.prototype.dispose = function () {
  67527. // Must be implemented by children
  67528. };
  67529. __decorate([
  67530. BABYLON.serialize()
  67531. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  67532. return PostProcessRenderPipeline;
  67533. }());
  67534. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  67535. })(BABYLON || (BABYLON = {}));
  67536. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  67537. var BABYLON;
  67538. (function (BABYLON) {
  67539. /**
  67540. * This represents a depth renderer in Babylon.
  67541. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  67542. */
  67543. var DepthRenderer = /** @class */ (function () {
  67544. /**
  67545. * Instantiates a depth renderer
  67546. * @param scene The scene the renderer belongs to
  67547. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  67548. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  67549. */
  67550. function DepthRenderer(scene, type, camera) {
  67551. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  67552. if (camera === void 0) { camera = null; }
  67553. var _this = this;
  67554. this._scene = scene;
  67555. this._camera = camera;
  67556. var engine = scene.getEngine();
  67557. // Render target
  67558. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  67559. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67560. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67561. this._depthMap.refreshRate = 1;
  67562. this._depthMap.renderParticles = false;
  67563. this._depthMap.renderList = null;
  67564. // Camera to get depth map from to support multiple concurrent cameras
  67565. this._depthMap.activeCamera = this._camera;
  67566. this._depthMap.ignoreCameraViewport = true;
  67567. this._depthMap.useCameraPostProcesses = false;
  67568. // set default depth value to 1.0 (far away)
  67569. this._depthMap.onClearObservable.add(function (engine) {
  67570. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  67571. });
  67572. // Custom render function
  67573. var renderSubMesh = function (subMesh) {
  67574. var mesh = subMesh.getRenderingMesh();
  67575. var scene = _this._scene;
  67576. var engine = scene.getEngine();
  67577. var material = subMesh.getMaterial();
  67578. if (!material) {
  67579. return;
  67580. }
  67581. // Culling and reverse (right handed system)
  67582. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  67583. // Managing instances
  67584. var batch = mesh._getInstancesRenderList(subMesh._id);
  67585. if (batch.mustReturn) {
  67586. return;
  67587. }
  67588. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  67589. var camera = _this._camera || scene.activeCamera;
  67590. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  67591. engine.enableEffect(_this._effect);
  67592. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  67593. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  67594. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  67595. // Alpha test
  67596. if (material && material.needAlphaTesting()) {
  67597. var alphaTexture = material.getAlphaTestTexture();
  67598. if (alphaTexture) {
  67599. _this._effect.setTexture("diffuseSampler", alphaTexture);
  67600. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67601. }
  67602. }
  67603. // Bones
  67604. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  67605. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67606. }
  67607. // Draw
  67608. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  67609. }
  67610. };
  67611. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67612. var index;
  67613. if (depthOnlySubMeshes.length) {
  67614. engine.setColorWrite(false);
  67615. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  67616. renderSubMesh(depthOnlySubMeshes.data[index]);
  67617. }
  67618. engine.setColorWrite(true);
  67619. }
  67620. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67621. renderSubMesh(opaqueSubMeshes.data[index]);
  67622. }
  67623. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67624. renderSubMesh(alphaTestSubMeshes.data[index]);
  67625. }
  67626. };
  67627. }
  67628. /**
  67629. * Creates the depth rendering effect and checks if the effect is ready.
  67630. * @param subMesh The submesh to be used to render the depth map of
  67631. * @param useInstances If multiple world instances should be used
  67632. * @returns if the depth renderer is ready to render the depth map
  67633. */
  67634. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  67635. var material = subMesh.getMaterial();
  67636. if (material.disableDepthWrite) {
  67637. return false;
  67638. }
  67639. var defines = [];
  67640. var attribs = [BABYLON.VertexBuffer.PositionKind];
  67641. var mesh = subMesh.getMesh();
  67642. // Alpha test
  67643. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  67644. defines.push("#define ALPHATEST");
  67645. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67646. attribs.push(BABYLON.VertexBuffer.UVKind);
  67647. defines.push("#define UV1");
  67648. }
  67649. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67650. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67651. defines.push("#define UV2");
  67652. }
  67653. }
  67654. // Bones
  67655. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67656. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67657. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67658. if (mesh.numBoneInfluencers > 4) {
  67659. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  67660. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  67661. }
  67662. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67663. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  67664. }
  67665. else {
  67666. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67667. }
  67668. // Instances
  67669. if (useInstances) {
  67670. defines.push("#define INSTANCES");
  67671. attribs.push("world0");
  67672. attribs.push("world1");
  67673. attribs.push("world2");
  67674. attribs.push("world3");
  67675. }
  67676. // Get correct effect
  67677. var join = defines.join("\n");
  67678. if (this._cachedDefines !== join) {
  67679. this._cachedDefines = join;
  67680. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  67681. }
  67682. return this._effect.isReady();
  67683. };
  67684. /**
  67685. * Gets the texture which the depth map will be written to.
  67686. * @returns The depth map texture
  67687. */
  67688. DepthRenderer.prototype.getDepthMap = function () {
  67689. return this._depthMap;
  67690. };
  67691. /**
  67692. * Disposes of the depth renderer.
  67693. */
  67694. DepthRenderer.prototype.dispose = function () {
  67695. this._depthMap.dispose();
  67696. };
  67697. return DepthRenderer;
  67698. }());
  67699. BABYLON.DepthRenderer = DepthRenderer;
  67700. })(BABYLON || (BABYLON = {}));
  67701. //# sourceMappingURL=babylon.depthRenderer.js.map
  67702. var BABYLON;
  67703. (function (BABYLON) {
  67704. var SSAORenderingPipeline = /** @class */ (function (_super) {
  67705. __extends(SSAORenderingPipeline, _super);
  67706. /**
  67707. * @constructor
  67708. * @param {string} name - The rendering pipeline name
  67709. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67710. * @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 }
  67711. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67712. */
  67713. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  67714. var _this = _super.call(this, scene.getEngine(), name) || this;
  67715. // Members
  67716. /**
  67717. * The PassPostProcess id in the pipeline that contains the original scene color
  67718. * @type {string}
  67719. */
  67720. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  67721. /**
  67722. * The SSAO PostProcess id in the pipeline
  67723. * @type {string}
  67724. */
  67725. _this.SSAORenderEffect = "SSAORenderEffect";
  67726. /**
  67727. * The horizontal blur PostProcess id in the pipeline
  67728. * @type {string}
  67729. */
  67730. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  67731. /**
  67732. * The vertical blur PostProcess id in the pipeline
  67733. * @type {string}
  67734. */
  67735. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  67736. /**
  67737. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  67738. * @type {string}
  67739. */
  67740. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  67741. /**
  67742. * The output strength of the SSAO post-process. Default value is 1.0.
  67743. * @type {number}
  67744. */
  67745. _this.totalStrength = 1.0;
  67746. /**
  67747. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  67748. * @type {number}
  67749. */
  67750. _this.radius = 0.0001;
  67751. /**
  67752. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  67753. * Must not be equal to fallOff and superior to fallOff.
  67754. * Default value is 0.975
  67755. * @type {number}
  67756. */
  67757. _this.area = 0.0075;
  67758. /**
  67759. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  67760. * Must not be equal to area and inferior to area.
  67761. * Default value is 0.0
  67762. * @type {number}
  67763. */
  67764. _this.fallOff = 0.000001;
  67765. /**
  67766. * The base color of the SSAO post-process
  67767. * The final result is "base + ssao" between [0, 1]
  67768. * @type {number}
  67769. */
  67770. _this.base = 0.5;
  67771. _this._firstUpdate = true;
  67772. _this._scene = scene;
  67773. // Set up assets
  67774. _this._createRandomTexture();
  67775. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  67776. var ssaoRatio = ratio.ssaoRatio || ratio;
  67777. var combineRatio = ratio.combineRatio || ratio;
  67778. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  67779. _this._createSSAOPostProcess(ssaoRatio);
  67780. _this._createBlurPostProcess(ssaoRatio);
  67781. _this._createSSAOCombinePostProcess(combineRatio);
  67782. // Set up pipeline
  67783. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  67784. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  67785. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  67786. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  67787. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  67788. // Finish
  67789. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67790. if (cameras)
  67791. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  67792. return _this;
  67793. }
  67794. // Public Methods
  67795. /**
  67796. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  67797. */
  67798. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  67799. if (disableDepthRender === void 0) { disableDepthRender = false; }
  67800. for (var i = 0; i < this._scene.cameras.length; i++) {
  67801. var camera = this._scene.cameras[i];
  67802. this._originalColorPostProcess.dispose(camera);
  67803. this._ssaoPostProcess.dispose(camera);
  67804. this._blurHPostProcess.dispose(camera);
  67805. this._blurVPostProcess.dispose(camera);
  67806. this._ssaoCombinePostProcess.dispose(camera);
  67807. }
  67808. this._randomTexture.dispose();
  67809. if (disableDepthRender)
  67810. this._scene.disableDepthRenderer();
  67811. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67812. _super.prototype.dispose.call(this);
  67813. };
  67814. // Private Methods
  67815. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  67816. var _this = this;
  67817. var size = 16;
  67818. 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);
  67819. 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);
  67820. this._blurHPostProcess.onActivateObservable.add(function () {
  67821. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  67822. _this._blurHPostProcess.kernel = size * dw;
  67823. });
  67824. this._blurVPostProcess.onActivateObservable.add(function () {
  67825. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  67826. _this._blurVPostProcess.kernel = size * dw;
  67827. });
  67828. };
  67829. SSAORenderingPipeline.prototype._rebuild = function () {
  67830. this._firstUpdate = true;
  67831. _super.prototype._rebuild.call(this);
  67832. };
  67833. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  67834. var _this = this;
  67835. var numSamples = 16;
  67836. var sampleSphere = [
  67837. 0.5381, 0.1856, -0.4319,
  67838. 0.1379, 0.2486, 0.4430,
  67839. 0.3371, 0.5679, -0.0057,
  67840. -0.6999, -0.0451, -0.0019,
  67841. 0.0689, -0.1598, -0.8547,
  67842. 0.0560, 0.0069, -0.1843,
  67843. -0.0146, 0.1402, 0.0762,
  67844. 0.0100, -0.1924, -0.0344,
  67845. -0.3577, -0.5301, -0.4358,
  67846. -0.3169, 0.1063, 0.0158,
  67847. 0.0103, -0.5869, 0.0046,
  67848. -0.0897, -0.4940, 0.3287,
  67849. 0.7119, -0.0154, -0.0918,
  67850. -0.0533, 0.0596, -0.5411,
  67851. 0.0352, -0.0631, 0.5460,
  67852. -0.4776, 0.2847, -0.0271
  67853. ];
  67854. var samplesFactor = 1.0 / numSamples;
  67855. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  67856. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  67857. "area", "fallOff", "base", "range", "viewport"
  67858. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  67859. this._ssaoPostProcess.onApply = function (effect) {
  67860. if (_this._firstUpdate) {
  67861. effect.setArray3("sampleSphere", sampleSphere);
  67862. effect.setFloat("samplesFactor", samplesFactor);
  67863. effect.setFloat("randTextureTiles", 4.0);
  67864. }
  67865. effect.setFloat("totalStrength", _this.totalStrength);
  67866. effect.setFloat("radius", _this.radius);
  67867. effect.setFloat("area", _this.area);
  67868. effect.setFloat("fallOff", _this.fallOff);
  67869. effect.setFloat("base", _this.base);
  67870. effect.setTexture("textureSampler", _this._depthTexture);
  67871. effect.setTexture("randomSampler", _this._randomTexture);
  67872. };
  67873. };
  67874. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  67875. var _this = this;
  67876. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67877. this._ssaoCombinePostProcess.onApply = function (effect) {
  67878. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  67879. };
  67880. };
  67881. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  67882. var size = 512;
  67883. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67884. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67885. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67886. var context = this._randomTexture.getContext();
  67887. var rand = function (min, max) {
  67888. return Math.random() * (max - min) + min;
  67889. };
  67890. var randVector = BABYLON.Vector3.Zero();
  67891. for (var x = 0; x < size; x++) {
  67892. for (var y = 0; y < size; y++) {
  67893. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  67894. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  67895. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  67896. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  67897. context.fillRect(x, y, 1, 1);
  67898. }
  67899. }
  67900. this._randomTexture.update(false);
  67901. };
  67902. __decorate([
  67903. BABYLON.serialize()
  67904. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  67905. __decorate([
  67906. BABYLON.serialize()
  67907. ], SSAORenderingPipeline.prototype, "radius", void 0);
  67908. __decorate([
  67909. BABYLON.serialize()
  67910. ], SSAORenderingPipeline.prototype, "area", void 0);
  67911. __decorate([
  67912. BABYLON.serialize()
  67913. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  67914. __decorate([
  67915. BABYLON.serialize()
  67916. ], SSAORenderingPipeline.prototype, "base", void 0);
  67917. return SSAORenderingPipeline;
  67918. }(BABYLON.PostProcessRenderPipeline));
  67919. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  67920. })(BABYLON || (BABYLON = {}));
  67921. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  67922. var BABYLON;
  67923. (function (BABYLON) {
  67924. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  67925. __extends(SSAO2RenderingPipeline, _super);
  67926. /**
  67927. * @constructor
  67928. * @param {string} name - The rendering pipeline name
  67929. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67930. * @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 }
  67931. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67932. */
  67933. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  67934. var _this = _super.call(this, scene.getEngine(), name) || this;
  67935. // Members
  67936. /**
  67937. * The PassPostProcess id in the pipeline that contains the original scene color
  67938. * @type {string}
  67939. */
  67940. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  67941. /**
  67942. * The SSAO PostProcess id in the pipeline
  67943. * @type {string}
  67944. */
  67945. _this.SSAORenderEffect = "SSAORenderEffect";
  67946. /**
  67947. * The horizontal blur PostProcess id in the pipeline
  67948. * @type {string}
  67949. */
  67950. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  67951. /**
  67952. * The vertical blur PostProcess id in the pipeline
  67953. * @type {string}
  67954. */
  67955. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  67956. /**
  67957. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  67958. * @type {string}
  67959. */
  67960. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  67961. /**
  67962. * The output strength of the SSAO post-process. Default value is 1.0.
  67963. * @type {number}
  67964. */
  67965. _this.totalStrength = 1.0;
  67966. /**
  67967. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  67968. * @type {number}
  67969. */
  67970. _this.maxZ = 100.0;
  67971. /**
  67972. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  67973. * @type {number}
  67974. */
  67975. _this.minZAspect = 0.2;
  67976. /**
  67977. * Number of samples used for the SSAO calculations. Default value is 8
  67978. * @type {number}
  67979. */
  67980. _this._samples = 8;
  67981. /**
  67982. * Are we using bilateral blur ?
  67983. * @type {boolean}
  67984. */
  67985. _this._expensiveBlur = true;
  67986. /**
  67987. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  67988. * @type {number}
  67989. */
  67990. _this.radius = 2.0;
  67991. /**
  67992. * The base color of the SSAO post-process
  67993. * The final result is "base + ssao" between [0, 1]
  67994. * @type {number}
  67995. */
  67996. _this.base = 0.1;
  67997. _this._firstUpdate = true;
  67998. _this._scene = scene;
  67999. if (!_this.isSupported) {
  68000. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  68001. return _this;
  68002. }
  68003. var ssaoRatio = ratio.ssaoRatio || ratio;
  68004. var blurRatio = ratio.blurRatio || ratio;
  68005. // Set up assets
  68006. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  68007. _this._createRandomTexture();
  68008. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  68009. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  68010. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  68011. _this._createSSAOPostProcess(1.0);
  68012. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  68013. _this._createSSAOCombinePostProcess(blurRatio);
  68014. // Set up pipeline
  68015. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  68016. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  68017. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  68018. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  68019. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  68020. // Finish
  68021. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68022. if (cameras)
  68023. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68024. return _this;
  68025. }
  68026. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  68027. get: function () {
  68028. return this._samples;
  68029. },
  68030. set: function (n) {
  68031. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  68032. this._samples = n;
  68033. this._sampleSphere = this._generateHemisphere();
  68034. this._firstUpdate = true;
  68035. },
  68036. enumerable: true,
  68037. configurable: true
  68038. });
  68039. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  68040. get: function () {
  68041. return this._expensiveBlur;
  68042. },
  68043. set: function (b) {
  68044. 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"]);
  68045. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  68046. this._expensiveBlur = b;
  68047. this._firstUpdate = true;
  68048. },
  68049. enumerable: true,
  68050. configurable: true
  68051. });
  68052. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  68053. /**
  68054. * Support test.
  68055. * @type {boolean}
  68056. */
  68057. get: function () {
  68058. var engine = BABYLON.Engine.LastCreatedEngine;
  68059. if (!engine) {
  68060. return false;
  68061. }
  68062. return engine.getCaps().drawBuffersExtension;
  68063. },
  68064. enumerable: true,
  68065. configurable: true
  68066. });
  68067. // Public Methods
  68068. /**
  68069. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  68070. */
  68071. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  68072. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  68073. for (var i = 0; i < this._scene.cameras.length; i++) {
  68074. var camera = this._scene.cameras[i];
  68075. this._originalColorPostProcess.dispose(camera);
  68076. this._ssaoPostProcess.dispose(camera);
  68077. this._blurHPostProcess.dispose(camera);
  68078. this._blurVPostProcess.dispose(camera);
  68079. this._ssaoCombinePostProcess.dispose(camera);
  68080. }
  68081. this._randomTexture.dispose();
  68082. if (disableGeometryBufferRenderer)
  68083. this._scene.disableGeometryBufferRenderer();
  68084. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68085. _super.prototype.dispose.call(this);
  68086. };
  68087. // Private Methods
  68088. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  68089. var _this = this;
  68090. this._samplerOffsets = [];
  68091. var expensive = this.expensiveBlur;
  68092. for (var i = -8; i < 8; i++) {
  68093. this._samplerOffsets.push(i * 2 + 0.5);
  68094. }
  68095. 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");
  68096. this._blurHPostProcess.onApply = function (effect) {
  68097. if (!_this._scene.activeCamera) {
  68098. return;
  68099. }
  68100. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  68101. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68102. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68103. effect.setFloat("radius", _this.radius);
  68104. effect.setTexture("depthSampler", _this._depthTexture);
  68105. if (_this._firstUpdate) {
  68106. effect.setArray("samplerOffsets", _this._samplerOffsets);
  68107. }
  68108. };
  68109. 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");
  68110. this._blurVPostProcess.onApply = function (effect) {
  68111. if (!_this._scene.activeCamera) {
  68112. return;
  68113. }
  68114. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  68115. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68116. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68117. effect.setFloat("radius", _this.radius);
  68118. effect.setTexture("depthSampler", _this._depthTexture);
  68119. if (_this._firstUpdate) {
  68120. effect.setArray("samplerOffsets", _this._samplerOffsets);
  68121. _this._firstUpdate = false;
  68122. }
  68123. };
  68124. };
  68125. SSAO2RenderingPipeline.prototype._rebuild = function () {
  68126. this._firstUpdate = true;
  68127. _super.prototype._rebuild.call(this);
  68128. };
  68129. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  68130. var numSamples = this.samples;
  68131. var result = [];
  68132. var vector, scale;
  68133. var rand = function (min, max) {
  68134. return Math.random() * (max - min) + min;
  68135. };
  68136. var i = 0;
  68137. while (i < numSamples) {
  68138. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  68139. vector.normalize();
  68140. scale = i / numSamples;
  68141. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  68142. vector.scaleInPlace(scale);
  68143. result.push(vector.x, vector.y, vector.z);
  68144. i++;
  68145. }
  68146. return result;
  68147. };
  68148. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  68149. var _this = this;
  68150. var numSamples = this.samples;
  68151. this._sampleSphere = this._generateHemisphere();
  68152. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  68153. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  68154. "base", "range", "projection", "near", "far", "texelSize",
  68155. "xViewport", "yViewport", "maxZ", "minZAspect"
  68156. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  68157. this._ssaoPostProcess.onApply = function (effect) {
  68158. if (_this._firstUpdate) {
  68159. effect.setArray3("sampleSphere", _this._sampleSphere);
  68160. effect.setFloat("randTextureTiles", 4.0);
  68161. }
  68162. if (!_this._scene.activeCamera) {
  68163. return;
  68164. }
  68165. effect.setFloat("samplesFactor", 1 / _this.samples);
  68166. effect.setFloat("totalStrength", _this.totalStrength);
  68167. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  68168. effect.setFloat("radius", _this.radius);
  68169. effect.setFloat("maxZ", _this.maxZ);
  68170. effect.setFloat("minZAspect", _this.minZAspect);
  68171. effect.setFloat("base", _this.base);
  68172. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68173. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68174. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  68175. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  68176. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  68177. effect.setTexture("textureSampler", _this._depthTexture);
  68178. effect.setTexture("normalSampler", _this._normalTexture);
  68179. effect.setTexture("randomSampler", _this._randomTexture);
  68180. };
  68181. };
  68182. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  68183. var _this = this;
  68184. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68185. this._ssaoCombinePostProcess.onApply = function (effect) {
  68186. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  68187. };
  68188. };
  68189. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  68190. var size = 512;
  68191. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  68192. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68193. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68194. var context = this._randomTexture.getContext();
  68195. var rand = function (min, max) {
  68196. return Math.random() * (max - min) + min;
  68197. };
  68198. var randVector = BABYLON.Vector3.Zero();
  68199. for (var x = 0; x < size; x++) {
  68200. for (var y = 0; y < size; y++) {
  68201. randVector.x = rand(0.0, 1.0);
  68202. randVector.y = rand(0.0, 1.0);
  68203. randVector.z = 0.0;
  68204. randVector.normalize();
  68205. randVector.scaleInPlace(255);
  68206. randVector.x = Math.floor(randVector.x);
  68207. randVector.y = Math.floor(randVector.y);
  68208. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  68209. context.fillRect(x, y, 1, 1);
  68210. }
  68211. }
  68212. this._randomTexture.update(false);
  68213. };
  68214. __decorate([
  68215. BABYLON.serialize()
  68216. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  68217. __decorate([
  68218. BABYLON.serialize()
  68219. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  68220. __decorate([
  68221. BABYLON.serialize()
  68222. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  68223. __decorate([
  68224. BABYLON.serialize("samples")
  68225. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  68226. __decorate([
  68227. BABYLON.serialize("expensiveBlur")
  68228. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  68229. __decorate([
  68230. BABYLON.serialize()
  68231. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  68232. __decorate([
  68233. BABYLON.serialize()
  68234. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  68235. return SSAO2RenderingPipeline;
  68236. }(BABYLON.PostProcessRenderPipeline));
  68237. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  68238. })(BABYLON || (BABYLON = {}));
  68239. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  68240. // BABYLON.JS Chromatic Aberration GLSL Shader
  68241. // Author: Olivier Guyot
  68242. // Separates very slightly R, G and B colors on the edges of the screen
  68243. // Inspired by Francois Tarlier & Martins Upitis
  68244. var BABYLON;
  68245. (function (BABYLON) {
  68246. var LensRenderingPipeline = /** @class */ (function (_super) {
  68247. __extends(LensRenderingPipeline, _super);
  68248. /**
  68249. * @constructor
  68250. *
  68251. * Effect parameters are as follow:
  68252. * {
  68253. * chromatic_aberration: number; // from 0 to x (1 for realism)
  68254. * edge_blur: number; // from 0 to x (1 for realism)
  68255. * distortion: number; // from 0 to x (1 for realism)
  68256. * grain_amount: number; // from 0 to 1
  68257. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  68258. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  68259. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  68260. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  68261. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  68262. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  68263. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  68264. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  68265. * }
  68266. * Note: if an effect parameter is unset, effect is disabled
  68267. *
  68268. * @param {string} name - The rendering pipeline name
  68269. * @param {object} parameters - An object containing all parameters (see above)
  68270. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68271. * @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)
  68272. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68273. */
  68274. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  68275. if (ratio === void 0) { ratio = 1.0; }
  68276. var _this = _super.call(this, scene.getEngine(), name) || this;
  68277. // Lens effects can be of the following:
  68278. // - chromatic aberration (slight shift of RGB colors)
  68279. // - blur on the edge of the lens
  68280. // - lens distortion
  68281. // - depth-of-field blur & highlights enhancing
  68282. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  68283. // - grain effect (noise or custom texture)
  68284. // Two additional texture samplers are needed:
  68285. // - depth map (for depth-of-field)
  68286. // - grain texture
  68287. /**
  68288. * The chromatic aberration PostProcess id in the pipeline
  68289. * @type {string}
  68290. */
  68291. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  68292. /**
  68293. * The highlights enhancing PostProcess id in the pipeline
  68294. * @type {string}
  68295. */
  68296. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  68297. /**
  68298. * The depth-of-field PostProcess id in the pipeline
  68299. * @type {string}
  68300. */
  68301. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  68302. _this._scene = scene;
  68303. // Fetch texture samplers
  68304. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  68305. if (parameters.grain_texture) {
  68306. _this._grainTexture = parameters.grain_texture;
  68307. }
  68308. else {
  68309. _this._createGrainTexture();
  68310. }
  68311. // save parameters
  68312. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  68313. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  68314. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  68315. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  68316. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  68317. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  68318. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  68319. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  68320. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  68321. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  68322. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  68323. // Create effects
  68324. _this._createChromaticAberrationPostProcess(ratio);
  68325. _this._createHighlightsPostProcess(ratio);
  68326. _this._createDepthOfFieldPostProcess(ratio / 4);
  68327. // Set up pipeline
  68328. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  68329. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  68330. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  68331. if (_this._highlightsGain === -1) {
  68332. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  68333. }
  68334. // Finish
  68335. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68336. if (cameras) {
  68337. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68338. }
  68339. return _this;
  68340. }
  68341. // public methods (self explanatory)
  68342. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  68343. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  68344. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  68345. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  68346. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  68347. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  68348. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  68349. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  68350. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  68351. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  68352. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  68353. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  68354. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  68355. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  68356. };
  68357. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  68358. this._highlightsPostProcess.updateEffect();
  68359. };
  68360. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  68361. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  68362. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  68363. this._highlightsGain = amount;
  68364. };
  68365. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  68366. if (this._highlightsGain === -1) {
  68367. this._highlightsGain = 1.0;
  68368. }
  68369. this._highlightsThreshold = amount;
  68370. };
  68371. LensRenderingPipeline.prototype.disableHighlights = function () {
  68372. this._highlightsGain = -1;
  68373. };
  68374. /**
  68375. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  68376. */
  68377. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  68378. if (disableDepthRender === void 0) { disableDepthRender = false; }
  68379. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68380. this._chromaticAberrationPostProcess = null;
  68381. this._highlightsPostProcess = null;
  68382. this._depthOfFieldPostProcess = null;
  68383. this._grainTexture.dispose();
  68384. if (disableDepthRender)
  68385. this._scene.disableDepthRenderer();
  68386. };
  68387. // colors shifting and distortion
  68388. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  68389. var _this = this;
  68390. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  68391. [], // samplers
  68392. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68393. this._chromaticAberrationPostProcess.onApply = function (effect) {
  68394. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  68395. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  68396. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  68397. effect.setFloat('radialIntensity', 1);
  68398. effect.setFloat2('direction', 17, 17);
  68399. effect.setFloat2('centerPosition', 0.5, 0.5);
  68400. };
  68401. };
  68402. // highlights enhancing
  68403. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  68404. var _this = this;
  68405. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  68406. [], // samplers
  68407. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  68408. this._highlightsPostProcess.onApply = function (effect) {
  68409. effect.setFloat('gain', _this._highlightsGain);
  68410. effect.setFloat('threshold', _this._highlightsThreshold);
  68411. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  68412. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  68413. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  68414. };
  68415. };
  68416. // colors shifting and distortion
  68417. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  68418. var _this = this;
  68419. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  68420. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  68421. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  68422. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68423. this._depthOfFieldPostProcess.onApply = function (effect) {
  68424. effect.setTexture("depthSampler", _this._depthTexture);
  68425. effect.setTexture("grainSampler", _this._grainTexture);
  68426. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  68427. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  68428. effect.setFloat('grain_amount', _this._grainAmount);
  68429. effect.setBool('blur_noise', _this._blurNoise);
  68430. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  68431. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  68432. effect.setFloat('distortion', _this._distortion);
  68433. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  68434. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  68435. effect.setFloat('aperture', _this._dofAperture);
  68436. effect.setFloat('darken', _this._dofDarken);
  68437. effect.setFloat('edge_blur', _this._edgeBlur);
  68438. effect.setBool('highlights', (_this._highlightsGain !== -1));
  68439. if (_this._scene.activeCamera) {
  68440. effect.setFloat('near', _this._scene.activeCamera.minZ);
  68441. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  68442. }
  68443. };
  68444. };
  68445. // creates a black and white random noise texture, 512x512
  68446. LensRenderingPipeline.prototype._createGrainTexture = function () {
  68447. var size = 512;
  68448. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68449. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68450. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68451. var context = this._grainTexture.getContext();
  68452. var rand = function (min, max) {
  68453. return Math.random() * (max - min) + min;
  68454. };
  68455. var value;
  68456. for (var x = 0; x < size; x++) {
  68457. for (var y = 0; y < size; y++) {
  68458. value = Math.floor(rand(0.42, 0.58) * 255);
  68459. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  68460. context.fillRect(x, y, 1, 1);
  68461. }
  68462. }
  68463. this._grainTexture.update(false);
  68464. };
  68465. return LensRenderingPipeline;
  68466. }(BABYLON.PostProcessRenderPipeline));
  68467. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  68468. })(BABYLON || (BABYLON = {}));
  68469. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  68470. var BABYLON;
  68471. (function (BABYLON) {
  68472. var StandardRenderingPipeline = /** @class */ (function (_super) {
  68473. __extends(StandardRenderingPipeline, _super);
  68474. /**
  68475. * @constructor
  68476. * @param {string} name - The rendering pipeline name
  68477. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68478. * @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)
  68479. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  68480. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68481. */
  68482. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  68483. if (originalPostProcess === void 0) { originalPostProcess = null; }
  68484. var _this = _super.call(this, scene.getEngine(), name) || this;
  68485. _this.downSampleX4PostProcess = null;
  68486. _this.brightPassPostProcess = null;
  68487. _this.blurHPostProcesses = [];
  68488. _this.blurVPostProcesses = [];
  68489. _this.textureAdderPostProcess = null;
  68490. _this.volumetricLightPostProcess = null;
  68491. _this.volumetricLightSmoothXPostProcess = null;
  68492. _this.volumetricLightSmoothYPostProcess = null;
  68493. _this.volumetricLightMergePostProces = null;
  68494. _this.volumetricLightFinalPostProcess = null;
  68495. _this.luminancePostProcess = null;
  68496. _this.luminanceDownSamplePostProcesses = [];
  68497. _this.hdrPostProcess = null;
  68498. _this.textureAdderFinalPostProcess = null;
  68499. _this.lensFlareFinalPostProcess = null;
  68500. _this.hdrFinalPostProcess = null;
  68501. _this.lensFlarePostProcess = null;
  68502. _this.lensFlareComposePostProcess = null;
  68503. _this.motionBlurPostProcess = null;
  68504. _this.depthOfFieldPostProcess = null;
  68505. // Values
  68506. _this.brightThreshold = 1.0;
  68507. _this.blurWidth = 512.0;
  68508. _this.horizontalBlur = false;
  68509. _this.exposure = 1.0;
  68510. _this.lensTexture = null;
  68511. _this.volumetricLightCoefficient = 0.2;
  68512. _this.volumetricLightPower = 4.0;
  68513. _this.volumetricLightBlurScale = 64.0;
  68514. _this.sourceLight = null;
  68515. _this.hdrMinimumLuminance = 1.0;
  68516. _this.hdrDecreaseRate = 0.5;
  68517. _this.hdrIncreaseRate = 0.5;
  68518. _this.lensColorTexture = null;
  68519. _this.lensFlareStrength = 20.0;
  68520. _this.lensFlareGhostDispersal = 1.4;
  68521. _this.lensFlareHaloWidth = 0.7;
  68522. _this.lensFlareDistortionStrength = 16.0;
  68523. _this.lensStarTexture = null;
  68524. _this.lensFlareDirtTexture = null;
  68525. _this.depthOfFieldDistance = 10.0;
  68526. _this.depthOfFieldBlurWidth = 64.0;
  68527. _this.motionStrength = 1.0;
  68528. // IAnimatable
  68529. _this.animations = [];
  68530. _this._currentDepthOfFieldSource = null;
  68531. _this._hdrCurrentLuminance = 1.0;
  68532. // Getters and setters
  68533. _this._bloomEnabled = true;
  68534. _this._depthOfFieldEnabled = false;
  68535. _this._vlsEnabled = false;
  68536. _this._lensFlareEnabled = false;
  68537. _this._hdrEnabled = false;
  68538. _this._motionBlurEnabled = false;
  68539. _this._motionBlurSamples = 64.0;
  68540. _this._volumetricLightStepsCount = 50.0;
  68541. _this._cameras = cameras || [];
  68542. // Initialize
  68543. _this._scene = scene;
  68544. _this._basePostProcess = originalPostProcess;
  68545. _this._ratio = ratio;
  68546. // Misc
  68547. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68548. // Finish
  68549. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68550. _this._buildPipeline();
  68551. return _this;
  68552. }
  68553. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  68554. get: function () {
  68555. return this._bloomEnabled;
  68556. },
  68557. set: function (enabled) {
  68558. if (this._bloomEnabled === enabled) {
  68559. return;
  68560. }
  68561. this._bloomEnabled = enabled;
  68562. this._buildPipeline();
  68563. },
  68564. enumerable: true,
  68565. configurable: true
  68566. });
  68567. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  68568. get: function () {
  68569. return this._depthOfFieldEnabled;
  68570. },
  68571. set: function (enabled) {
  68572. if (this._depthOfFieldEnabled === enabled) {
  68573. return;
  68574. }
  68575. this._depthOfFieldEnabled = enabled;
  68576. this._buildPipeline();
  68577. },
  68578. enumerable: true,
  68579. configurable: true
  68580. });
  68581. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  68582. get: function () {
  68583. return this._lensFlareEnabled;
  68584. },
  68585. set: function (enabled) {
  68586. if (this._lensFlareEnabled === enabled) {
  68587. return;
  68588. }
  68589. this._lensFlareEnabled = enabled;
  68590. this._buildPipeline();
  68591. },
  68592. enumerable: true,
  68593. configurable: true
  68594. });
  68595. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  68596. get: function () {
  68597. return this._hdrEnabled;
  68598. },
  68599. set: function (enabled) {
  68600. if (this._hdrEnabled === enabled) {
  68601. return;
  68602. }
  68603. this._hdrEnabled = enabled;
  68604. this._buildPipeline();
  68605. },
  68606. enumerable: true,
  68607. configurable: true
  68608. });
  68609. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  68610. get: function () {
  68611. return this._vlsEnabled;
  68612. },
  68613. set: function (enabled) {
  68614. if (this._vlsEnabled === enabled) {
  68615. return;
  68616. }
  68617. if (enabled) {
  68618. var geometry = this._scene.enableGeometryBufferRenderer();
  68619. if (!geometry) {
  68620. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  68621. return;
  68622. }
  68623. }
  68624. this._vlsEnabled = enabled;
  68625. this._buildPipeline();
  68626. },
  68627. enumerable: true,
  68628. configurable: true
  68629. });
  68630. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  68631. get: function () {
  68632. return this._motionBlurEnabled;
  68633. },
  68634. set: function (enabled) {
  68635. if (this._motionBlurEnabled === enabled) {
  68636. return;
  68637. }
  68638. this._motionBlurEnabled = enabled;
  68639. this._buildPipeline();
  68640. },
  68641. enumerable: true,
  68642. configurable: true
  68643. });
  68644. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  68645. get: function () {
  68646. return this._volumetricLightStepsCount;
  68647. },
  68648. set: function (count) {
  68649. if (this.volumetricLightPostProcess) {
  68650. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  68651. }
  68652. this._volumetricLightStepsCount = count;
  68653. },
  68654. enumerable: true,
  68655. configurable: true
  68656. });
  68657. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  68658. get: function () {
  68659. return this._motionBlurSamples;
  68660. },
  68661. set: function (samples) {
  68662. if (this.motionBlurPostProcess) {
  68663. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  68664. }
  68665. this._motionBlurSamples = samples;
  68666. },
  68667. enumerable: true,
  68668. configurable: true
  68669. });
  68670. StandardRenderingPipeline.prototype._buildPipeline = function () {
  68671. var _this = this;
  68672. var ratio = this._ratio;
  68673. var scene = this._scene;
  68674. this._disposePostProcesses();
  68675. this._reset();
  68676. // Create pass post-process
  68677. if (!this._basePostProcess) {
  68678. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  68679. this.originalPostProcess.onApply = function (effect) {
  68680. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  68681. };
  68682. }
  68683. else {
  68684. this.originalPostProcess = this._basePostProcess;
  68685. }
  68686. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  68687. this._currentDepthOfFieldSource = this.originalPostProcess;
  68688. if (this._vlsEnabled) {
  68689. // Create volumetric light
  68690. this._createVolumetricLightPostProcess(scene, ratio);
  68691. // Create volumetric light final post-process
  68692. 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);
  68693. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  68694. }
  68695. if (this._bloomEnabled) {
  68696. // Create down sample X4 post-process
  68697. this._createDownSampleX4PostProcess(scene, ratio / 2);
  68698. // Create bright pass post-process
  68699. this._createBrightPassPostProcess(scene, ratio / 2);
  68700. // Create gaussian blur post-processes (down sampling blurs)
  68701. this._createBlurPostProcesses(scene, ratio / 4, 1);
  68702. // Create texture adder post-process
  68703. this._createTextureAdderPostProcess(scene, ratio);
  68704. // Create depth-of-field source post-process
  68705. 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);
  68706. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  68707. }
  68708. if (this._lensFlareEnabled) {
  68709. // Create lens flare post-process
  68710. this._createLensFlarePostProcess(scene, ratio);
  68711. // Create depth-of-field source post-process post lens-flare and disable it now
  68712. 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);
  68713. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  68714. }
  68715. if (this._hdrEnabled) {
  68716. // Create luminance
  68717. this._createLuminancePostProcesses(scene, this._floatTextureType);
  68718. // Create HDR
  68719. this._createHdrPostProcess(scene, ratio);
  68720. // Create depth-of-field source post-process post hdr and disable it now
  68721. 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);
  68722. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  68723. }
  68724. if (this._depthOfFieldEnabled) {
  68725. // Create gaussian blur used by depth-of-field
  68726. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  68727. // Create depth-of-field post-process
  68728. this._createDepthOfFieldPostProcess(scene, ratio);
  68729. }
  68730. if (this._motionBlurEnabled) {
  68731. // Create motion blur post-process
  68732. this._createMotionBlurPostProcess(scene, ratio);
  68733. }
  68734. if (this._cameras !== null) {
  68735. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  68736. }
  68737. };
  68738. // Down Sample X4 Post-Processs
  68739. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  68740. var _this = this;
  68741. var downSampleX4Offsets = new Array(32);
  68742. 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);
  68743. this.downSampleX4PostProcess.onApply = function (effect) {
  68744. var id = 0;
  68745. var width = _this.downSampleX4PostProcess.width;
  68746. var height = _this.downSampleX4PostProcess.height;
  68747. for (var i = -2; i < 2; i++) {
  68748. for (var j = -2; j < 2; j++) {
  68749. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  68750. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  68751. id += 2;
  68752. }
  68753. }
  68754. effect.setArray2("dsOffsets", downSampleX4Offsets);
  68755. };
  68756. // Add to pipeline
  68757. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  68758. };
  68759. // Brightpass Post-Process
  68760. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  68761. var _this = this;
  68762. var brightOffsets = new Array(8);
  68763. 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);
  68764. this.brightPassPostProcess.onApply = function (effect) {
  68765. var sU = (1.0 / _this.brightPassPostProcess.width);
  68766. var sV = (1.0 / _this.brightPassPostProcess.height);
  68767. brightOffsets[0] = -0.5 * sU;
  68768. brightOffsets[1] = 0.5 * sV;
  68769. brightOffsets[2] = 0.5 * sU;
  68770. brightOffsets[3] = 0.5 * sV;
  68771. brightOffsets[4] = -0.5 * sU;
  68772. brightOffsets[5] = -0.5 * sV;
  68773. brightOffsets[6] = 0.5 * sU;
  68774. brightOffsets[7] = -0.5 * sV;
  68775. effect.setArray2("dsOffsets", brightOffsets);
  68776. effect.setFloat("brightThreshold", _this.brightThreshold);
  68777. };
  68778. // Add to pipeline
  68779. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  68780. };
  68781. // Create blur H&V post-processes
  68782. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  68783. var _this = this;
  68784. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  68785. var engine = scene.getEngine();
  68786. 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);
  68787. 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);
  68788. blurX.onActivateObservable.add(function () {
  68789. var dw = blurX.width / engine.getRenderWidth();
  68790. blurX.kernel = _this[blurWidthKey] * dw;
  68791. });
  68792. blurY.onActivateObservable.add(function () {
  68793. var dw = blurY.height / engine.getRenderHeight();
  68794. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  68795. });
  68796. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  68797. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  68798. this.blurHPostProcesses.push(blurX);
  68799. this.blurVPostProcesses.push(blurY);
  68800. };
  68801. // Create texture adder post-process
  68802. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  68803. var _this = this;
  68804. 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);
  68805. this.textureAdderPostProcess.onApply = function (effect) {
  68806. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  68807. effect.setTexture("lensSampler", _this.lensTexture);
  68808. effect.setFloat("exposure", _this.exposure);
  68809. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  68810. };
  68811. // Add to pipeline
  68812. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  68813. };
  68814. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  68815. var _this = this;
  68816. var geometryRenderer = scene.enableGeometryBufferRenderer();
  68817. geometryRenderer.enablePosition = true;
  68818. var geometry = geometryRenderer.getGBuffer();
  68819. // Base post-process
  68820. 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));
  68821. var depthValues = BABYLON.Vector2.Zero();
  68822. this.volumetricLightPostProcess.onApply = function (effect) {
  68823. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  68824. var generator = _this.sourceLight.getShadowGenerator();
  68825. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  68826. effect.setTexture("positionSampler", geometry.textures[2]);
  68827. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  68828. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  68829. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  68830. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  68831. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  68832. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  68833. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  68834. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  68835. effect.setVector2("depthValues", depthValues);
  68836. }
  68837. };
  68838. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  68839. // Smooth
  68840. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  68841. // Merge
  68842. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  68843. this.volumetricLightMergePostProces.onApply = function (effect) {
  68844. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  68845. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  68846. };
  68847. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  68848. };
  68849. // Create luminance
  68850. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  68851. var _this = this;
  68852. // Create luminance
  68853. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  68854. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  68855. var offsets = [];
  68856. this.luminancePostProcess.onApply = function (effect) {
  68857. var sU = (1.0 / _this.luminancePostProcess.width);
  68858. var sV = (1.0 / _this.luminancePostProcess.height);
  68859. offsets[0] = -0.5 * sU;
  68860. offsets[1] = 0.5 * sV;
  68861. offsets[2] = 0.5 * sU;
  68862. offsets[3] = 0.5 * sV;
  68863. offsets[4] = -0.5 * sU;
  68864. offsets[5] = -0.5 * sV;
  68865. offsets[6] = 0.5 * sU;
  68866. offsets[7] = -0.5 * sV;
  68867. effect.setArray2("lumOffsets", offsets);
  68868. };
  68869. // Add to pipeline
  68870. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  68871. // Create down sample luminance
  68872. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  68873. var size = Math.pow(3, i);
  68874. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  68875. if (i === 0) {
  68876. defines += "#define FINAL_DOWN_SAMPLER";
  68877. }
  68878. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  68879. this.luminanceDownSamplePostProcesses.push(postProcess);
  68880. }
  68881. // Create callbacks and add effects
  68882. var lastLuminance = this.luminancePostProcess;
  68883. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  68884. var downSampleOffsets = new Array(18);
  68885. pp.onApply = function (effect) {
  68886. if (!lastLuminance) {
  68887. return;
  68888. }
  68889. var id = 0;
  68890. for (var x = -1; x < 2; x++) {
  68891. for (var y = -1; y < 2; y++) {
  68892. downSampleOffsets[id] = x / lastLuminance.width;
  68893. downSampleOffsets[id + 1] = y / lastLuminance.height;
  68894. id += 2;
  68895. }
  68896. }
  68897. effect.setArray2("dsOffsets", downSampleOffsets);
  68898. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  68899. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  68900. lastLuminance = _this.luminancePostProcess;
  68901. }
  68902. else {
  68903. lastLuminance = pp;
  68904. }
  68905. };
  68906. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  68907. pp.onAfterRender = function (effect) {
  68908. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  68909. 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);
  68910. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  68911. };
  68912. }
  68913. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  68914. });
  68915. };
  68916. // Create HDR post-process
  68917. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  68918. var _this = this;
  68919. 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);
  68920. var outputLiminance = 1;
  68921. var time = 0;
  68922. var lastTime = 0;
  68923. this.hdrPostProcess.onApply = function (effect) {
  68924. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  68925. time += scene.getEngine().getDeltaTime();
  68926. if (outputLiminance < 0) {
  68927. outputLiminance = _this._hdrCurrentLuminance;
  68928. }
  68929. else {
  68930. var dt = (lastTime - time) / 1000.0;
  68931. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  68932. outputLiminance += _this.hdrDecreaseRate * dt;
  68933. }
  68934. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  68935. outputLiminance -= _this.hdrIncreaseRate * dt;
  68936. }
  68937. else {
  68938. outputLiminance = _this._hdrCurrentLuminance;
  68939. }
  68940. }
  68941. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  68942. effect.setFloat("averageLuminance", outputLiminance);
  68943. lastTime = time;
  68944. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  68945. };
  68946. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  68947. };
  68948. // Create lens flare post-process
  68949. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  68950. var _this = this;
  68951. 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);
  68952. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  68953. this._createBlurPostProcesses(scene, ratio / 4, 2);
  68954. 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);
  68955. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  68956. var resolution = new BABYLON.Vector2(0, 0);
  68957. // Lens flare
  68958. this.lensFlarePostProcess.onApply = function (effect) {
  68959. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  68960. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  68961. effect.setFloat("strength", _this.lensFlareStrength);
  68962. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  68963. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  68964. // Shift
  68965. resolution.x = _this.lensFlarePostProcess.width;
  68966. resolution.y = _this.lensFlarePostProcess.height;
  68967. effect.setVector2("resolution", resolution);
  68968. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  68969. };
  68970. // Compose
  68971. 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);
  68972. 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);
  68973. this.lensFlareComposePostProcess.onApply = function (effect) {
  68974. if (!_this._scene.activeCamera) {
  68975. return;
  68976. }
  68977. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  68978. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  68979. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  68980. // Lens start rotation matrix
  68981. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  68982. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  68983. 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));
  68984. camRot *= 4.0;
  68985. 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);
  68986. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  68987. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  68988. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  68989. };
  68990. };
  68991. // Create depth-of-field post-process
  68992. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  68993. var _this = this;
  68994. 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);
  68995. this.depthOfFieldPostProcess.onApply = function (effect) {
  68996. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  68997. effect.setTexture("depthSampler", _this._getDepthTexture());
  68998. effect.setFloat("distance", _this.depthOfFieldDistance);
  68999. };
  69000. // Add to pipeline
  69001. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  69002. };
  69003. // Create motion blur post-process
  69004. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  69005. var _this = this;
  69006. 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);
  69007. var motionScale = 0;
  69008. var prevViewProjection = BABYLON.Matrix.Identity();
  69009. var invViewProjection = BABYLON.Matrix.Identity();
  69010. var viewProjection = BABYLON.Matrix.Identity();
  69011. var screenSize = BABYLON.Vector2.Zero();
  69012. this.motionBlurPostProcess.onApply = function (effect) {
  69013. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  69014. viewProjection.invertToRef(invViewProjection);
  69015. effect.setMatrix("inverseViewProjection", invViewProjection);
  69016. effect.setMatrix("prevViewProjection", prevViewProjection);
  69017. prevViewProjection = viewProjection;
  69018. screenSize.x = _this.motionBlurPostProcess.width;
  69019. screenSize.y = _this.motionBlurPostProcess.height;
  69020. effect.setVector2("screenSize", screenSize);
  69021. motionScale = scene.getEngine().getFps() / 60.0;
  69022. effect.setFloat("motionScale", motionScale);
  69023. effect.setFloat("motionStrength", _this.motionStrength);
  69024. effect.setTexture("depthSampler", _this._getDepthTexture());
  69025. };
  69026. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  69027. };
  69028. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  69029. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  69030. var renderer = this._scene.enableGeometryBufferRenderer();
  69031. return renderer.getGBuffer().textures[0];
  69032. }
  69033. return this._scene.enableDepthRenderer().getDepthMap();
  69034. };
  69035. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  69036. for (var i = 0; i < this._cameras.length; i++) {
  69037. var camera = this._cameras[i];
  69038. if (this.originalPostProcess) {
  69039. this.originalPostProcess.dispose(camera);
  69040. }
  69041. if (this.downSampleX4PostProcess) {
  69042. this.downSampleX4PostProcess.dispose(camera);
  69043. }
  69044. if (this.brightPassPostProcess) {
  69045. this.brightPassPostProcess.dispose(camera);
  69046. }
  69047. if (this.textureAdderPostProcess) {
  69048. this.textureAdderPostProcess.dispose(camera);
  69049. }
  69050. if (this.textureAdderFinalPostProcess) {
  69051. this.textureAdderFinalPostProcess.dispose(camera);
  69052. }
  69053. if (this.volumetricLightPostProcess) {
  69054. this.volumetricLightPostProcess.dispose(camera);
  69055. }
  69056. if (this.volumetricLightSmoothXPostProcess) {
  69057. this.volumetricLightSmoothXPostProcess.dispose(camera);
  69058. }
  69059. if (this.volumetricLightSmoothYPostProcess) {
  69060. this.volumetricLightSmoothYPostProcess.dispose(camera);
  69061. }
  69062. if (this.volumetricLightMergePostProces) {
  69063. this.volumetricLightMergePostProces.dispose(camera);
  69064. }
  69065. if (this.volumetricLightFinalPostProcess) {
  69066. this.volumetricLightFinalPostProcess.dispose(camera);
  69067. }
  69068. if (this.lensFlarePostProcess) {
  69069. this.lensFlarePostProcess.dispose(camera);
  69070. }
  69071. if (this.lensFlareComposePostProcess) {
  69072. this.lensFlareComposePostProcess.dispose(camera);
  69073. }
  69074. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  69075. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  69076. }
  69077. if (this.luminancePostProcess) {
  69078. this.luminancePostProcess.dispose(camera);
  69079. }
  69080. if (this.hdrPostProcess) {
  69081. this.hdrPostProcess.dispose(camera);
  69082. }
  69083. if (this.hdrFinalPostProcess) {
  69084. this.hdrFinalPostProcess.dispose(camera);
  69085. }
  69086. if (this.depthOfFieldPostProcess) {
  69087. this.depthOfFieldPostProcess.dispose(camera);
  69088. }
  69089. if (this.motionBlurPostProcess) {
  69090. this.motionBlurPostProcess.dispose(camera);
  69091. }
  69092. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  69093. this.blurHPostProcesses[j].dispose(camera);
  69094. }
  69095. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  69096. this.blurVPostProcesses[j].dispose(camera);
  69097. }
  69098. }
  69099. this.originalPostProcess = null;
  69100. this.downSampleX4PostProcess = null;
  69101. this.brightPassPostProcess = null;
  69102. this.textureAdderPostProcess = null;
  69103. this.textureAdderFinalPostProcess = null;
  69104. this.volumetricLightPostProcess = null;
  69105. this.volumetricLightSmoothXPostProcess = null;
  69106. this.volumetricLightSmoothYPostProcess = null;
  69107. this.volumetricLightMergePostProces = null;
  69108. this.volumetricLightFinalPostProcess = null;
  69109. this.lensFlarePostProcess = null;
  69110. this.lensFlareComposePostProcess = null;
  69111. this.luminancePostProcess = null;
  69112. this.hdrPostProcess = null;
  69113. this.hdrFinalPostProcess = null;
  69114. this.depthOfFieldPostProcess = null;
  69115. this.motionBlurPostProcess = null;
  69116. this.luminanceDownSamplePostProcesses = [];
  69117. this.blurHPostProcesses = [];
  69118. this.blurVPostProcesses = [];
  69119. };
  69120. // Dispose
  69121. StandardRenderingPipeline.prototype.dispose = function () {
  69122. this._disposePostProcesses();
  69123. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  69124. _super.prototype.dispose.call(this);
  69125. };
  69126. // Serialize rendering pipeline
  69127. StandardRenderingPipeline.prototype.serialize = function () {
  69128. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  69129. serializationObject.customType = "StandardRenderingPipeline";
  69130. return serializationObject;
  69131. };
  69132. /**
  69133. * Static members
  69134. */
  69135. // Parse serialized pipeline
  69136. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  69137. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  69138. };
  69139. // Luminance steps
  69140. StandardRenderingPipeline.LuminanceSteps = 6;
  69141. __decorate([
  69142. BABYLON.serialize()
  69143. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  69144. __decorate([
  69145. BABYLON.serialize()
  69146. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  69147. __decorate([
  69148. BABYLON.serialize()
  69149. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  69150. __decorate([
  69151. BABYLON.serialize()
  69152. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  69153. __decorate([
  69154. BABYLON.serializeAsTexture("lensTexture")
  69155. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  69156. __decorate([
  69157. BABYLON.serialize()
  69158. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  69159. __decorate([
  69160. BABYLON.serialize()
  69161. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  69162. __decorate([
  69163. BABYLON.serialize()
  69164. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  69165. __decorate([
  69166. BABYLON.serialize()
  69167. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  69168. __decorate([
  69169. BABYLON.serialize()
  69170. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  69171. __decorate([
  69172. BABYLON.serialize()
  69173. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  69174. __decorate([
  69175. BABYLON.serializeAsTexture("lensColorTexture")
  69176. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  69177. __decorate([
  69178. BABYLON.serialize()
  69179. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  69180. __decorate([
  69181. BABYLON.serialize()
  69182. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  69183. __decorate([
  69184. BABYLON.serialize()
  69185. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  69186. __decorate([
  69187. BABYLON.serialize()
  69188. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  69189. __decorate([
  69190. BABYLON.serializeAsTexture("lensStarTexture")
  69191. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  69192. __decorate([
  69193. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  69194. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  69195. __decorate([
  69196. BABYLON.serialize()
  69197. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  69198. __decorate([
  69199. BABYLON.serialize()
  69200. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  69201. __decorate([
  69202. BABYLON.serialize()
  69203. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  69204. __decorate([
  69205. BABYLON.serialize()
  69206. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  69207. __decorate([
  69208. BABYLON.serialize()
  69209. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  69210. __decorate([
  69211. BABYLON.serialize()
  69212. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  69213. __decorate([
  69214. BABYLON.serialize()
  69215. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  69216. __decorate([
  69217. BABYLON.serialize()
  69218. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  69219. __decorate([
  69220. BABYLON.serialize()
  69221. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  69222. __decorate([
  69223. BABYLON.serialize()
  69224. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  69225. __decorate([
  69226. BABYLON.serialize()
  69227. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  69228. __decorate([
  69229. BABYLON.serialize()
  69230. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  69231. return StandardRenderingPipeline;
  69232. }(BABYLON.PostProcessRenderPipeline));
  69233. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  69234. })(BABYLON || (BABYLON = {}));
  69235. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  69236. var BABYLON;
  69237. (function (BABYLON) {
  69238. var FxaaPostProcess = /** @class */ (function (_super) {
  69239. __extends(FxaaPostProcess, _super);
  69240. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  69241. if (camera === void 0) { camera = null; }
  69242. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69243. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  69244. _this.onApplyObservable.add(function (effect) {
  69245. var texelSize = _this.texelSize;
  69246. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  69247. });
  69248. return _this;
  69249. }
  69250. return FxaaPostProcess;
  69251. }(BABYLON.PostProcess));
  69252. BABYLON.FxaaPostProcess = FxaaPostProcess;
  69253. })(BABYLON || (BABYLON = {}));
  69254. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  69255. var BABYLON;
  69256. (function (BABYLON) {
  69257. /**
  69258. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  69259. */
  69260. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  69261. __extends(ChromaticAberrationPostProcess, _super);
  69262. /**
  69263. * Creates a new instance of @see ChromaticAberrationPostProcess
  69264. * @param name The name of the effect.
  69265. * @param screenWidth The width of the screen to apply the effect on.
  69266. * @param screenHeight The height of the screen to apply the effect on.
  69267. * @param options The required width/height ratio to downsize to before computing the render pass.
  69268. * @param camera The camera to apply the render pass to.
  69269. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69270. * @param engine The engine which the post process will be applied. (default: current engine)
  69271. * @param reusable If the post process can be reused on the same frame. (default: false)
  69272. * @param textureType Type of textures used when performing the post process. (default: 0)
  69273. * @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)
  69274. */
  69275. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69276. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69277. if (blockCompilation === void 0) { blockCompilation = false; }
  69278. 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;
  69279. /**
  69280. * The amount of seperation of rgb channels (default: 30)
  69281. */
  69282. _this.aberrationAmount = 30;
  69283. /**
  69284. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  69285. */
  69286. _this.radialIntensity = 0;
  69287. /**
  69288. * 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))
  69289. */
  69290. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  69291. /**
  69292. * 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))
  69293. */
  69294. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  69295. _this.onApplyObservable.add(function (effect) {
  69296. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  69297. effect.setFloat('screen_width', screenWidth);
  69298. effect.setFloat('screen_height', screenHeight);
  69299. effect.setFloat('radialIntensity', _this.radialIntensity);
  69300. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  69301. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  69302. });
  69303. return _this;
  69304. }
  69305. return ChromaticAberrationPostProcess;
  69306. }(BABYLON.PostProcess));
  69307. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  69308. })(BABYLON || (BABYLON = {}));
  69309. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  69310. var BABYLON;
  69311. (function (BABYLON) {
  69312. /**
  69313. * The SharpenPostProcess applies a sharpen kernel to every pixel
  69314. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  69315. */
  69316. var SharpenPostProcess = /** @class */ (function (_super) {
  69317. __extends(SharpenPostProcess, _super);
  69318. /**
  69319. * Creates a new instance of @see ConvolutionPostProcess
  69320. * @param name The name of the effect.
  69321. * @param options The required width/height ratio to downsize to before computing the render pass.
  69322. * @param camera The camera to apply the render pass to.
  69323. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69324. * @param engine The engine which the post process will be applied. (default: current engine)
  69325. * @param reusable If the post process can be reused on the same frame. (default: false)
  69326. * @param textureType Type of textures used when performing the post process. (default: 0)
  69327. * @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)
  69328. */
  69329. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69330. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69331. if (blockCompilation === void 0) { blockCompilation = false; }
  69332. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  69333. /**
  69334. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  69335. */
  69336. _this.colorAmount = 1.0;
  69337. /**
  69338. * How much sharpness should be applied (default: 0.3)
  69339. */
  69340. _this.edgeAmount = 0.3;
  69341. _this.onApply = function (effect) {
  69342. effect.setFloat2("screenSize", _this.width, _this.height);
  69343. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  69344. };
  69345. return _this;
  69346. }
  69347. return SharpenPostProcess;
  69348. }(BABYLON.PostProcess));
  69349. BABYLON.SharpenPostProcess = SharpenPostProcess;
  69350. })(BABYLON || (BABYLON = {}));
  69351. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  69352. var BABYLON;
  69353. (function (BABYLON) {
  69354. /**
  69355. * The Blur Post Process which blurs an image based on a kernel and direction.
  69356. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  69357. */
  69358. var BlurPostProcess = /** @class */ (function (_super) {
  69359. __extends(BlurPostProcess, _super);
  69360. /**
  69361. * Creates a new instance of @see BlurPostProcess
  69362. * @param name The name of the effect.
  69363. * @param direction The direction in which to blur the image.
  69364. * @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.
  69365. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  69366. * @param camera The camera to apply the render pass to.
  69367. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69368. * @param engine The engine which the post process will be applied. (default: current engine)
  69369. * @param reusable If the post process can be reused on the same frame. (default: false)
  69370. * @param textureType Type of textures used when performing the post process. (default: 0)
  69371. * @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)
  69372. */
  69373. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  69374. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69375. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69376. if (defines === void 0) { defines = ""; }
  69377. if (blockCompilation === void 0) { blockCompilation = false; }
  69378. 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;
  69379. _this.direction = direction;
  69380. _this.blockCompilation = blockCompilation;
  69381. _this._packedFloat = false;
  69382. _this._staticDefines = "";
  69383. _this._staticDefines = defines;
  69384. _this.onApplyObservable.add(function (effect) {
  69385. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  69386. });
  69387. _this.kernel = kernel;
  69388. return _this;
  69389. }
  69390. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  69391. /**
  69392. * Gets the length in pixels of the blur sample region
  69393. */
  69394. get: function () {
  69395. return this._idealKernel;
  69396. },
  69397. /**
  69398. * Sets the length in pixels of the blur sample region
  69399. */
  69400. set: function (v) {
  69401. if (this._idealKernel === v) {
  69402. return;
  69403. }
  69404. v = Math.max(v, 1);
  69405. this._idealKernel = v;
  69406. this._kernel = this._nearestBestKernel(v);
  69407. if (!this.blockCompilation) {
  69408. this._updateParameters();
  69409. }
  69410. },
  69411. enumerable: true,
  69412. configurable: true
  69413. });
  69414. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  69415. /**
  69416. * Gets wether or not the blur is unpacking/repacking floats
  69417. */
  69418. get: function () {
  69419. return this._packedFloat;
  69420. },
  69421. /**
  69422. * Sets wether or not the blur needs to unpack/repack floats
  69423. */
  69424. set: function (v) {
  69425. if (this._packedFloat === v) {
  69426. return;
  69427. }
  69428. this._packedFloat = v;
  69429. if (!this.blockCompilation) {
  69430. this._updateParameters();
  69431. }
  69432. },
  69433. enumerable: true,
  69434. configurable: true
  69435. });
  69436. /**
  69437. * Updates the effect with the current post process compile time values and recompiles the shader.
  69438. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  69439. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  69440. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  69441. * @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
  69442. * @param onCompiled Called when the shader has been compiled.
  69443. * @param onError Called if there is an error when compiling a shader.
  69444. */
  69445. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  69446. if (defines === void 0) { defines = null; }
  69447. if (uniforms === void 0) { uniforms = null; }
  69448. if (samplers === void 0) { samplers = null; }
  69449. this._updateParameters(onCompiled, onError);
  69450. };
  69451. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  69452. // Generate sampling offsets and weights
  69453. var N = this._kernel;
  69454. var centerIndex = (N - 1) / 2;
  69455. // Generate Gaussian sampling weights over kernel
  69456. var offsets = [];
  69457. var weights = [];
  69458. var totalWeight = 0;
  69459. for (var i = 0; i < N; i++) {
  69460. var u = i / (N - 1);
  69461. var w = this._gaussianWeight(u * 2.0 - 1);
  69462. offsets[i] = (i - centerIndex);
  69463. weights[i] = w;
  69464. totalWeight += w;
  69465. }
  69466. // Normalize weights
  69467. for (var i = 0; i < weights.length; i++) {
  69468. weights[i] /= totalWeight;
  69469. }
  69470. // Optimize: combine samples to take advantage of hardware linear sampling
  69471. // Walk from left to center, combining pairs (symmetrically)
  69472. var linearSamplingWeights = [];
  69473. var linearSamplingOffsets = [];
  69474. var linearSamplingMap = [];
  69475. for (var i = 0; i <= centerIndex; i += 2) {
  69476. var j = Math.min(i + 1, Math.floor(centerIndex));
  69477. var singleCenterSample = i === j;
  69478. if (singleCenterSample) {
  69479. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69480. }
  69481. else {
  69482. var sharedCell = j === centerIndex;
  69483. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  69484. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  69485. if (offsetLinear === 0) {
  69486. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69487. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  69488. }
  69489. else {
  69490. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  69491. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  69492. }
  69493. }
  69494. }
  69495. for (var i = 0; i < linearSamplingMap.length; i++) {
  69496. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  69497. linearSamplingWeights[i] = linearSamplingMap[i].w;
  69498. }
  69499. // Replace with optimized
  69500. offsets = linearSamplingOffsets;
  69501. weights = linearSamplingWeights;
  69502. // Generate shaders
  69503. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  69504. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  69505. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  69506. var defines = "";
  69507. defines += this._staticDefines;
  69508. for (var i = 0; i < varyingCount; i++) {
  69509. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  69510. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  69511. }
  69512. var depCount = 0;
  69513. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  69514. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  69515. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  69516. depCount++;
  69517. }
  69518. if (this.packedFloat) {
  69519. defines += "#define PACKEDFLOAT 1";
  69520. }
  69521. _super.prototype.updateEffect.call(this, defines, null, null, {
  69522. varyingCount: varyingCount,
  69523. depCount: depCount
  69524. }, onCompiled, onError);
  69525. };
  69526. /**
  69527. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  69528. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  69529. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  69530. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  69531. * The gaps between physical kernels are compensated for in the weighting of the samples
  69532. * @param idealKernel Ideal blur kernel.
  69533. * @return Nearest best kernel.
  69534. */
  69535. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  69536. var v = Math.round(idealKernel);
  69537. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  69538. var k = _a[_i];
  69539. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  69540. return Math.max(k, 3);
  69541. }
  69542. }
  69543. return Math.max(v, 3);
  69544. };
  69545. /**
  69546. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  69547. * @param x The point on the Gaussian distribution to sample.
  69548. * @return the value of the Gaussian function at x.
  69549. */
  69550. BlurPostProcess.prototype._gaussianWeight = function (x) {
  69551. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  69552. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  69553. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  69554. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  69555. // truncated at around 1.3% of peak strength.
  69556. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  69557. var sigma = (1 / 3);
  69558. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  69559. var exponent = -((x * x) / (2.0 * sigma * sigma));
  69560. var weight = (1.0 / denominator) * Math.exp(exponent);
  69561. return weight;
  69562. };
  69563. /**
  69564. * Generates a string that can be used as a floating point number in GLSL.
  69565. * @param x Value to print.
  69566. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  69567. * @return GLSL float string.
  69568. */
  69569. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  69570. if (decimalFigures === void 0) { decimalFigures = 8; }
  69571. return x.toFixed(decimalFigures).replace(/0+$/, '');
  69572. };
  69573. return BlurPostProcess;
  69574. }(BABYLON.PostProcess));
  69575. BABYLON.BlurPostProcess = BlurPostProcess;
  69576. })(BABYLON || (BABYLON = {}));
  69577. //# sourceMappingURL=babylon.blurPostProcess.js.map
  69578. var BABYLON;
  69579. (function (BABYLON) {
  69580. /**
  69581. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  69582. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  69583. * based on samples that have a large difference in distance than the center pixel.
  69584. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  69585. */
  69586. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  69587. __extends(DepthOfFieldBlurPostProcess, _super);
  69588. /**
  69589. * Creates a new instance of @see CircleOfConfusionPostProcess
  69590. * @param name The name of the effect.
  69591. * @param scene The scene the effect belongs to.
  69592. * @param direction The direction the blur should be applied.
  69593. * @param kernel The size of the kernel used to blur.
  69594. * @param options The required width/height ratio to downsize to before computing the render pass.
  69595. * @param camera The camera to apply the render pass to.
  69596. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  69597. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  69598. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69599. * @param engine The engine which the post process will be applied. (default: current engine)
  69600. * @param reusable If the post process can be reused on the same frame. (default: false)
  69601. * @param textureType Type of textures used when performing the post process. (default: 0)
  69602. * @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)
  69603. */
  69604. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  69605. if (imageToBlur === void 0) { imageToBlur = null; }
  69606. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69607. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69608. if (blockCompilation === void 0) { blockCompilation = false; }
  69609. 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;
  69610. _this.direction = direction;
  69611. _this.onApplyObservable.add(function (effect) {
  69612. if (imageToBlur != null) {
  69613. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  69614. }
  69615. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  69616. if (scene.activeCamera) {
  69617. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  69618. }
  69619. });
  69620. return _this;
  69621. }
  69622. return DepthOfFieldBlurPostProcess;
  69623. }(BABYLON.BlurPostProcess));
  69624. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  69625. })(BABYLON || (BABYLON = {}));
  69626. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  69627. var BABYLON;
  69628. (function (BABYLON) {
  69629. /**
  69630. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  69631. */
  69632. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  69633. __extends(DepthOfFieldMergePostProcess, _super);
  69634. /**
  69635. * Creates a new instance of @see CircleOfConfusionPostProcess
  69636. * @param name The name of the effect.
  69637. * @param original The non-blurred image to be modified
  69638. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  69639. * @param blurSteps Incrimental bluring post processes.
  69640. * @param options The required width/height ratio to downsize to before computing the render pass.
  69641. * @param camera The camera to apply the render pass to.
  69642. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69643. * @param engine The engine which the post process will be applied. (default: current engine)
  69644. * @param reusable If the post process can be reused on the same frame. (default: false)
  69645. * @param textureType Type of textures used when performing the post process. (default: 0)
  69646. * @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)
  69647. */
  69648. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69649. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69650. if (blockCompilation === void 0) { blockCompilation = false; }
  69651. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  69652. _this.blurSteps = blurSteps;
  69653. _this.onApplyObservable.add(function (effect) {
  69654. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  69655. effect.setTextureFromPostProcess("originalSampler", original);
  69656. blurSteps.forEach(function (step, index) {
  69657. effect.setTextureFromPostProcess("blurStep" + (index + 1), step);
  69658. });
  69659. });
  69660. if (!blockCompilation) {
  69661. _this.updateEffect();
  69662. }
  69663. return _this;
  69664. }
  69665. /**
  69666. * Updates the effect with the current post process compile time values and recompiles the shader.
  69667. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  69668. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  69669. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  69670. * @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
  69671. * @param onCompiled Called when the shader has been compiled.
  69672. * @param onError Called if there is an error when compiling a shader.
  69673. */
  69674. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  69675. if (defines === void 0) { defines = null; }
  69676. if (uniforms === void 0) { uniforms = null; }
  69677. if (samplers === void 0) { samplers = null; }
  69678. _super.prototype.updateEffect.call(this, defines ? defines : "#define BLUR_LEVEL " + this.blurSteps.length + "\n", uniforms, samplers, indexParameters, onCompiled, onError);
  69679. };
  69680. return DepthOfFieldMergePostProcess;
  69681. }(BABYLON.PostProcess));
  69682. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  69683. })(BABYLON || (BABYLON = {}));
  69684. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  69685. var BABYLON;
  69686. (function (BABYLON) {
  69687. /**
  69688. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  69689. */
  69690. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  69691. __extends(CircleOfConfusionPostProcess, _super);
  69692. /**
  69693. * Creates a new instance of @see CircleOfConfusionPostProcess
  69694. * @param name The name of the effect.
  69695. * @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.
  69696. * @param options The required width/height ratio to downsize to before computing the render pass.
  69697. * @param camera The camera to apply the render pass to.
  69698. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69699. * @param engine The engine which the post process will be applied. (default: current engine)
  69700. * @param reusable If the post process can be reused on the same frame. (default: false)
  69701. * @param textureType Type of textures used when performing the post process. (default: 0)
  69702. * @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)
  69703. */
  69704. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69705. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69706. if (blockCompilation === void 0) { blockCompilation = false; }
  69707. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  69708. /**
  69709. * 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.
  69710. */
  69711. _this.lensSize = 50;
  69712. /**
  69713. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  69714. */
  69715. _this.fStop = 1.4;
  69716. /**
  69717. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  69718. */
  69719. _this.focusDistance = 2000;
  69720. /**
  69721. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  69722. */
  69723. _this.focalLength = 50;
  69724. _this._depthTexture = null;
  69725. _this._depthTexture = depthTexture;
  69726. _this.onApplyObservable.add(function (effect) {
  69727. if (!_this._depthTexture) {
  69728. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  69729. return;
  69730. }
  69731. effect.setTexture("depthSampler", _this._depthTexture);
  69732. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  69733. var aperture = _this.lensSize / _this.fStop;
  69734. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  69735. effect.setFloat('focusDistance', _this.focusDistance);
  69736. effect.setFloat('cocPrecalculation', cocPrecalculation);
  69737. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  69738. });
  69739. return _this;
  69740. }
  69741. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  69742. /**
  69743. * 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.
  69744. */
  69745. set: function (value) {
  69746. this._depthTexture = value;
  69747. },
  69748. enumerable: true,
  69749. configurable: true
  69750. });
  69751. return CircleOfConfusionPostProcess;
  69752. }(BABYLON.PostProcess));
  69753. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  69754. })(BABYLON || (BABYLON = {}));
  69755. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  69756. var BABYLON;
  69757. (function (BABYLON) {
  69758. /**
  69759. * Specifies the level of max blur that should be applied when using the depth of field effect
  69760. */
  69761. var DepthOfFieldEffectBlurLevel;
  69762. (function (DepthOfFieldEffectBlurLevel) {
  69763. /**
  69764. * Subtle blur
  69765. */
  69766. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  69767. /**
  69768. * Medium blur
  69769. */
  69770. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  69771. /**
  69772. * Large blur
  69773. */
  69774. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  69775. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  69776. ;
  69777. /**
  69778. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  69779. */
  69780. var DepthOfFieldEffect = /** @class */ (function (_super) {
  69781. __extends(DepthOfFieldEffect, _super);
  69782. /**
  69783. * Creates a new instance of @see DepthOfFieldEffect
  69784. * @param scene The scene the effect belongs to.
  69785. * @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.
  69786. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  69787. * @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)
  69788. */
  69789. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  69790. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  69791. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  69792. if (blockCompilation === void 0) { blockCompilation = false; }
  69793. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  69794. return _this._effects;
  69795. }, true) || this;
  69796. _this._effects = [];
  69797. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  69798. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69799. // Capture circle of confusion texture
  69800. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69801. _this._depthOfFieldPass.autoClear = false;
  69802. // 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)
  69803. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  69804. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  69805. _this._depthOfFieldBlurY = [];
  69806. _this._depthOfFieldBlurX = [];
  69807. var blurCount = 1;
  69808. var kernelSize = 15;
  69809. switch (blurLevel) {
  69810. case DepthOfFieldEffectBlurLevel.High: {
  69811. blurCount = 3;
  69812. kernelSize = 51;
  69813. break;
  69814. }
  69815. case DepthOfFieldEffectBlurLevel.Medium: {
  69816. blurCount = 2;
  69817. kernelSize = 31;
  69818. break;
  69819. }
  69820. default: {
  69821. kernelSize = 15;
  69822. blurCount = 1;
  69823. break;
  69824. }
  69825. }
  69826. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  69827. for (var i = 0; i < blurCount; i++) {
  69828. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69829. blurY.autoClear = false;
  69830. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69831. blurX.autoClear = false;
  69832. _this._depthOfFieldBlurY.push(blurY);
  69833. _this._depthOfFieldBlurX.push(blurX);
  69834. }
  69835. // Merge blurred images with original image based on circleOfConfusion
  69836. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY.slice(1), 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69837. _this._depthOfFieldMerge.autoClear = false;
  69838. // Set all post processes on the effect.
  69839. _this._effects = [_this._circleOfConfusion, _this._depthOfFieldPass];
  69840. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  69841. _this._effects.push(_this._depthOfFieldBlurY[i]);
  69842. _this._effects.push(_this._depthOfFieldBlurX[i]);
  69843. }
  69844. _this._effects.push(_this._depthOfFieldMerge);
  69845. return _this;
  69846. }
  69847. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  69848. get: function () {
  69849. return this._circleOfConfusion.focalLength;
  69850. },
  69851. /**
  69852. * The focal the length of the camera used in the effect
  69853. */
  69854. set: function (value) {
  69855. this._circleOfConfusion.focalLength = value;
  69856. },
  69857. enumerable: true,
  69858. configurable: true
  69859. });
  69860. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  69861. get: function () {
  69862. return this._circleOfConfusion.fStop;
  69863. },
  69864. /**
  69865. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  69866. */
  69867. set: function (value) {
  69868. this._circleOfConfusion.fStop = value;
  69869. },
  69870. enumerable: true,
  69871. configurable: true
  69872. });
  69873. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  69874. get: function () {
  69875. return this._circleOfConfusion.focusDistance;
  69876. },
  69877. /**
  69878. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  69879. */
  69880. set: function (value) {
  69881. this._circleOfConfusion.focusDistance = value;
  69882. },
  69883. enumerable: true,
  69884. configurable: true
  69885. });
  69886. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  69887. get: function () {
  69888. return this._circleOfConfusion.lensSize;
  69889. },
  69890. /**
  69891. * 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.
  69892. */
  69893. set: function (value) {
  69894. this._circleOfConfusion.lensSize = value;
  69895. },
  69896. enumerable: true,
  69897. configurable: true
  69898. });
  69899. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  69900. /**
  69901. * 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.
  69902. */
  69903. set: function (value) {
  69904. this._circleOfConfusion.depthTexture = value;
  69905. },
  69906. enumerable: true,
  69907. configurable: true
  69908. });
  69909. /**
  69910. * Disposes each of the internal effects for a given camera.
  69911. * @param camera The camera to dispose the effect on.
  69912. */
  69913. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  69914. this._depthOfFieldPass.dispose(camera);
  69915. this._circleOfConfusion.dispose(camera);
  69916. this._depthOfFieldBlurX.forEach(function (element) {
  69917. element.dispose(camera);
  69918. });
  69919. this._depthOfFieldBlurY.forEach(function (element) {
  69920. element.dispose(camera);
  69921. });
  69922. this._depthOfFieldMerge.dispose(camera);
  69923. };
  69924. /**
  69925. * Internal
  69926. */
  69927. DepthOfFieldEffect.prototype._updateEffects = function () {
  69928. for (var effect in this._effects) {
  69929. this._effects[effect].updateEffect();
  69930. }
  69931. };
  69932. /**
  69933. * Internal
  69934. * @returns if all the contained post processes are ready.
  69935. */
  69936. DepthOfFieldEffect.prototype._isReady = function () {
  69937. for (var effect in this._effects) {
  69938. if (!this._effects[effect].isReady()) {
  69939. return false;
  69940. }
  69941. }
  69942. return true;
  69943. };
  69944. return DepthOfFieldEffect;
  69945. }(BABYLON.PostProcessRenderEffect));
  69946. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  69947. })(BABYLON || (BABYLON = {}));
  69948. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  69949. var BABYLON;
  69950. (function (BABYLON) {
  69951. /**
  69952. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  69953. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  69954. */
  69955. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  69956. __extends(DefaultRenderingPipeline, _super);
  69957. /**
  69958. * @constructor
  69959. * @param {string} name - The rendering pipeline name
  69960. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  69961. * @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)
  69962. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  69963. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  69964. */
  69965. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  69966. if (automaticBuild === void 0) { automaticBuild = true; }
  69967. var _this = _super.call(this, scene.getEngine(), name) || this;
  69968. _this._originalCameras = [];
  69969. /**
  69970. * ID of the sharpen post process,
  69971. */
  69972. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  69973. /**
  69974. * ID of the pass post process used for bloom,
  69975. */
  69976. _this.PassPostProcessId = "PassPostProcessEffect";
  69977. /**
  69978. * ID of the highlight post process used for bloom,
  69979. */
  69980. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  69981. /**
  69982. * ID of the blurX post process used for bloom,
  69983. */
  69984. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  69985. /**
  69986. * ID of the blurY post process used for bloom,
  69987. */
  69988. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  69989. /**
  69990. * ID of the copy back post process used for bloom,
  69991. */
  69992. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  69993. /**
  69994. * ID of the image processing post process;
  69995. */
  69996. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  69997. /**
  69998. * ID of the Fast Approximate Anti-Aliasing post process;
  69999. */
  70000. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  70001. /**
  70002. * ID of the final merge post process;
  70003. */
  70004. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  70005. /**
  70006. * ID of the chromatic aberration post process,
  70007. */
  70008. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  70009. /**
  70010. * Animations which can be used to tweak settings over a period of time
  70011. */
  70012. _this.animations = [];
  70013. // Values
  70014. _this._sharpenEnabled = false;
  70015. _this._bloomEnabled = false;
  70016. _this._depthOfFieldEnabled = false;
  70017. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  70018. _this._fxaaEnabled = false;
  70019. _this._msaaEnabled = false;
  70020. _this._imageProcessingEnabled = true;
  70021. _this._bloomScale = 0.6;
  70022. _this._chromaticAberrationEnabled = false;
  70023. _this._buildAllowed = true;
  70024. /**
  70025. * Specifies the size of the bloom blur kernel, relative to the final output size
  70026. */
  70027. _this.bloomKernel = 64;
  70028. /**
  70029. * Specifies the weight of the bloom in the final rendering
  70030. */
  70031. _this._bloomWeight = 0.15;
  70032. _this._prevPostProcess = null;
  70033. _this._prevPrevPostProcess = null;
  70034. _this._cameras = cameras || [];
  70035. _this._originalCameras = _this._cameras.slice();
  70036. _this._buildAllowed = automaticBuild;
  70037. // Initialize
  70038. _this._scene = scene;
  70039. var caps = _this._scene.getEngine().getCaps();
  70040. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  70041. // Misc
  70042. if (_this._hdr) {
  70043. if (caps.textureHalfFloatRender) {
  70044. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70045. }
  70046. else if (caps.textureFloatRender) {
  70047. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70048. }
  70049. }
  70050. else {
  70051. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70052. }
  70053. // Attach
  70054. scene.postProcessRenderPipelineManager.addPipeline(_this);
  70055. var engine = _this._scene.getEngine();
  70056. // Create post processes before hand so they can be modified before enabled.
  70057. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  70058. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  70059. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  70060. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  70061. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  70062. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  70063. _this._buildPipeline();
  70064. return _this;
  70065. }
  70066. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  70067. get: function () {
  70068. return this._sharpenEnabled;
  70069. },
  70070. /**
  70071. * Enable or disable the sharpen process from the pipeline
  70072. */
  70073. set: function (enabled) {
  70074. if (this._sharpenEnabled === enabled) {
  70075. return;
  70076. }
  70077. this._sharpenEnabled = enabled;
  70078. this._buildPipeline();
  70079. },
  70080. enumerable: true,
  70081. configurable: true
  70082. });
  70083. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  70084. get: function () {
  70085. return this._bloomWeight;
  70086. },
  70087. /**
  70088. * The strength of the bloom.
  70089. */
  70090. set: function (value) {
  70091. if (this._bloomWeight === value) {
  70092. return;
  70093. }
  70094. this._bloomWeight = value;
  70095. if (this._hdr && this.copyBack) {
  70096. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  70097. }
  70098. },
  70099. enumerable: true,
  70100. configurable: true
  70101. });
  70102. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  70103. get: function () {
  70104. return this._bloomScale;
  70105. },
  70106. /**
  70107. * The scale of the bloom, lower value will provide better performance.
  70108. */
  70109. set: function (value) {
  70110. if (this._bloomScale === value) {
  70111. return;
  70112. }
  70113. this._bloomScale = value;
  70114. this._buildPipeline();
  70115. },
  70116. enumerable: true,
  70117. configurable: true
  70118. });
  70119. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  70120. get: function () {
  70121. return this._bloomEnabled;
  70122. },
  70123. /**
  70124. * Enable or disable the bloom from the pipeline
  70125. */
  70126. set: function (enabled) {
  70127. if (this._bloomEnabled === enabled) {
  70128. return;
  70129. }
  70130. this._bloomEnabled = enabled;
  70131. this._buildPipeline();
  70132. },
  70133. enumerable: true,
  70134. configurable: true
  70135. });
  70136. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  70137. /**
  70138. * If the depth of field is enabled.
  70139. */
  70140. get: function () {
  70141. return this._depthOfFieldEnabled;
  70142. },
  70143. set: function (enabled) {
  70144. if (this._depthOfFieldEnabled === enabled) {
  70145. return;
  70146. }
  70147. this._depthOfFieldEnabled = enabled;
  70148. this._buildPipeline();
  70149. },
  70150. enumerable: true,
  70151. configurable: true
  70152. });
  70153. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  70154. /**
  70155. * Blur level of the depth of field effect. (Higher blur will effect performance)
  70156. */
  70157. get: function () {
  70158. return this._depthOfFieldBlurLevel;
  70159. },
  70160. set: function (value) {
  70161. if (this._depthOfFieldBlurLevel === value) {
  70162. return;
  70163. }
  70164. this._depthOfFieldBlurLevel = value;
  70165. // recreate dof and dispose old as this setting is not dynamic
  70166. var oldDof = this.depthOfField;
  70167. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  70168. this.depthOfField.focalLength = oldDof.focalLength;
  70169. this.depthOfField.focusDistance = oldDof.focusDistance;
  70170. this.depthOfField.fStop = oldDof.fStop;
  70171. this.depthOfField.lensSize = oldDof.lensSize;
  70172. for (var i = 0; i < this._cameras.length; i++) {
  70173. oldDof.disposeEffects(this._cameras[i]);
  70174. }
  70175. this._buildPipeline();
  70176. },
  70177. enumerable: true,
  70178. configurable: true
  70179. });
  70180. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  70181. get: function () {
  70182. return this._fxaaEnabled;
  70183. },
  70184. /**
  70185. * If the anti aliasing is enabled.
  70186. */
  70187. set: function (enabled) {
  70188. if (this._fxaaEnabled === enabled) {
  70189. return;
  70190. }
  70191. this._fxaaEnabled = enabled;
  70192. this._buildPipeline();
  70193. },
  70194. enumerable: true,
  70195. configurable: true
  70196. });
  70197. Object.defineProperty(DefaultRenderingPipeline.prototype, "msaaEnabled", {
  70198. get: function () {
  70199. return this._msaaEnabled;
  70200. },
  70201. /**
  70202. * If the multisample anti-aliasing is enabled.
  70203. */
  70204. set: function (enabled) {
  70205. if (this._msaaEnabled === enabled) {
  70206. return;
  70207. }
  70208. this._msaaEnabled = enabled;
  70209. this._buildPipeline();
  70210. },
  70211. enumerable: true,
  70212. configurable: true
  70213. });
  70214. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  70215. get: function () {
  70216. return this._imageProcessingEnabled;
  70217. },
  70218. /**
  70219. * If image processing is enabled.
  70220. */
  70221. set: function (enabled) {
  70222. if (this._imageProcessingEnabled === enabled) {
  70223. return;
  70224. }
  70225. this._imageProcessingEnabled = enabled;
  70226. this._buildPipeline();
  70227. },
  70228. enumerable: true,
  70229. configurable: true
  70230. });
  70231. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  70232. get: function () {
  70233. return this._chromaticAberrationEnabled;
  70234. },
  70235. /**
  70236. * Enable or disable the chromaticAberration process from the pipeline
  70237. */
  70238. set: function (enabled) {
  70239. if (this._chromaticAberrationEnabled === enabled) {
  70240. return;
  70241. }
  70242. this._chromaticAberrationEnabled = enabled;
  70243. this._buildPipeline();
  70244. },
  70245. enumerable: true,
  70246. configurable: true
  70247. });
  70248. /**
  70249. * Force the compilation of the entire pipeline.
  70250. */
  70251. DefaultRenderingPipeline.prototype.prepare = function () {
  70252. var previousState = this._buildAllowed;
  70253. this._buildAllowed = true;
  70254. this._buildPipeline();
  70255. this._buildAllowed = previousState;
  70256. };
  70257. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  70258. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  70259. if (this._prevPostProcess && this._prevPostProcess.autoClear) {
  70260. postProcess.autoClear = false;
  70261. }
  70262. else {
  70263. postProcess.autoClear = true;
  70264. }
  70265. if (!skipTextureSharing) {
  70266. if (this._prevPrevPostProcess) {
  70267. postProcess.shareOutputWith(this._prevPrevPostProcess);
  70268. }
  70269. else {
  70270. postProcess.useOwnOutput();
  70271. }
  70272. if (this._prevPostProcess) {
  70273. this._prevPrevPostProcess = this._prevPostProcess;
  70274. }
  70275. this._prevPostProcess = postProcess;
  70276. }
  70277. };
  70278. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  70279. var _this = this;
  70280. if (!this._buildAllowed) {
  70281. return;
  70282. }
  70283. var engine = this._scene.getEngine();
  70284. this._disposePostProcesses();
  70285. if (this._cameras !== null) {
  70286. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  70287. // get back cameras to be used to reattach pipeline
  70288. this._cameras = this._originalCameras.slice();
  70289. }
  70290. this._reset();
  70291. this._prevPostProcess = null;
  70292. this._prevPrevPostProcess = null;
  70293. if (this.sharpenEnabled) {
  70294. if (!this.sharpen.isReady()) {
  70295. this.sharpen.updateEffect();
  70296. }
  70297. this.addEffect(this._sharpenEffect);
  70298. this._setAutoClearAndTextureSharing(this.sharpen);
  70299. }
  70300. if (this.depthOfFieldEnabled) {
  70301. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  70302. this.depthOfField.depthTexture = depthTexture;
  70303. if (!this.depthOfField._isReady()) {
  70304. this.depthOfField._updateEffects();
  70305. }
  70306. this.addEffect(this.depthOfField);
  70307. this._setAutoClearAndTextureSharing(this.depthOfField._depthOfFieldMerge);
  70308. }
  70309. if (this.bloomEnabled) {
  70310. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70311. this._setAutoClearAndTextureSharing(this.pass, true);
  70312. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  70313. if (!this._hdr) {
  70314. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70315. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  70316. this.highlights.autoClear = false;
  70317. this.highlights.alwaysForcePOT = true;
  70318. }
  70319. this.blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70320. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  70321. this.blurX.alwaysForcePOT = true;
  70322. this.blurX.autoClear = false;
  70323. this.blurX.onActivateObservable.add(function () {
  70324. var dw = _this.blurX.width / engine.getRenderWidth(true);
  70325. _this.blurX.kernel = _this.bloomKernel * dw;
  70326. });
  70327. this.blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70328. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  70329. this.blurY.alwaysForcePOT = true;
  70330. this.blurY.autoClear = false;
  70331. this.blurY.onActivateObservable.add(function () {
  70332. var dh = _this.blurY.height / engine.getRenderHeight(true);
  70333. _this.blurY.kernel = _this.bloomKernel * dh;
  70334. });
  70335. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70336. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  70337. this.copyBack.alwaysForcePOT = true;
  70338. if (this._hdr) {
  70339. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  70340. var w = this.bloomWeight;
  70341. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  70342. }
  70343. else {
  70344. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  70345. }
  70346. this.copyBack.autoClear = false;
  70347. }
  70348. if (this._imageProcessingEnabled) {
  70349. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70350. if (this._hdr) {
  70351. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  70352. }
  70353. else {
  70354. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  70355. }
  70356. }
  70357. if (this._hdr && this.imageProcessing) {
  70358. this.finalMerge = this.imageProcessing;
  70359. }
  70360. else {
  70361. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70362. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  70363. this._setAutoClearAndTextureSharing(this.finalMerge, true);
  70364. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  70365. }
  70366. if (this.bloomEnabled) {
  70367. if (this._hdr) {
  70368. this.copyBack.shareOutputWith(this.blurX);
  70369. if (this.imageProcessing) {
  70370. this.imageProcessing.shareOutputWith(this.pass);
  70371. this.imageProcessing.autoClear = false;
  70372. }
  70373. else {
  70374. this.finalMerge.shareOutputWith(this.pass);
  70375. }
  70376. }
  70377. else {
  70378. this.finalMerge.shareOutputWith(this.pass);
  70379. }
  70380. }
  70381. if (this.fxaaEnabled) {
  70382. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70383. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  70384. this._setAutoClearAndTextureSharing(this.fxaa);
  70385. }
  70386. if (this.chromaticAberrationEnabled) {
  70387. if (!this.chromaticAberration.isReady()) {
  70388. this.chromaticAberration.updateEffect();
  70389. }
  70390. this.addEffect(this._chromaticAberrationEffect);
  70391. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  70392. }
  70393. if (this._cameras !== null) {
  70394. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  70395. }
  70396. if (this.msaaEnabled) {
  70397. if (!this._enableMSAAOnFirstPostProcess()) {
  70398. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  70399. }
  70400. }
  70401. };
  70402. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  70403. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  70404. for (var i = 0; i < this._cameras.length; i++) {
  70405. var camera = this._cameras[i];
  70406. if (this.pass) {
  70407. this.pass.dispose(camera);
  70408. }
  70409. if (this.highlights) {
  70410. this.highlights.dispose(camera);
  70411. }
  70412. if (this.blurX) {
  70413. this.blurX.dispose(camera);
  70414. }
  70415. if (this.blurY) {
  70416. this.blurY.dispose(camera);
  70417. }
  70418. if (this.copyBack) {
  70419. this.copyBack.dispose(camera);
  70420. }
  70421. if (this.imageProcessing) {
  70422. this.imageProcessing.dispose(camera);
  70423. }
  70424. if (this.fxaa) {
  70425. this.fxaa.dispose(camera);
  70426. }
  70427. if (this.finalMerge) {
  70428. this.finalMerge.dispose(camera);
  70429. }
  70430. // These are created in the constructor and should not be disposed on every pipeline change
  70431. if (disposeNonRecreated) {
  70432. if (this.sharpen) {
  70433. this.sharpen.dispose(camera);
  70434. }
  70435. if (this.depthOfField) {
  70436. this.depthOfField.disposeEffects(camera);
  70437. }
  70438. if (this.chromaticAberration) {
  70439. this.chromaticAberration.dispose(camera);
  70440. }
  70441. }
  70442. }
  70443. this.pass = null;
  70444. this.highlights = null;
  70445. this.blurX = null;
  70446. this.blurY = null;
  70447. this.copyBack = null;
  70448. this.imageProcessing = null;
  70449. this.fxaa = null;
  70450. this.finalMerge = null;
  70451. if (disposeNonRecreated) {
  70452. this.sharpen = null;
  70453. this.depthOfField = null;
  70454. this.chromaticAberration = null;
  70455. }
  70456. };
  70457. /**
  70458. * Dispose of the pipeline and stop all post processes
  70459. */
  70460. DefaultRenderingPipeline.prototype.dispose = function () {
  70461. this._disposePostProcesses(true);
  70462. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  70463. _super.prototype.dispose.call(this);
  70464. };
  70465. /**
  70466. * Serialize the rendering pipeline (Used when exporting)
  70467. * @returns the serialized object
  70468. */
  70469. DefaultRenderingPipeline.prototype.serialize = function () {
  70470. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  70471. serializationObject.customType = "DefaultRenderingPipeline";
  70472. return serializationObject;
  70473. };
  70474. /**
  70475. * Parse the serialized pipeline
  70476. * @param source Source pipeline.
  70477. * @param scene The scene to load the pipeline to.
  70478. * @param rootUrl The URL of the serialized pipeline.
  70479. * @returns An instantiated pipeline from the serialized object.
  70480. */
  70481. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  70482. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  70483. };
  70484. __decorate([
  70485. BABYLON.serialize()
  70486. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  70487. __decorate([
  70488. BABYLON.serialize()
  70489. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  70490. __decorate([
  70491. BABYLON.serialize()
  70492. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  70493. __decorate([
  70494. BABYLON.serialize()
  70495. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  70496. __decorate([
  70497. BABYLON.serialize()
  70498. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  70499. __decorate([
  70500. BABYLON.serialize()
  70501. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  70502. __decorate([
  70503. BABYLON.serialize()
  70504. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  70505. __decorate([
  70506. BABYLON.serialize()
  70507. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  70508. __decorate([
  70509. BABYLON.serialize()
  70510. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  70511. __decorate([
  70512. BABYLON.serialize()
  70513. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  70514. __decorate([
  70515. BABYLON.serialize()
  70516. ], DefaultRenderingPipeline.prototype, "msaaEnabled", null);
  70517. __decorate([
  70518. BABYLON.serialize()
  70519. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  70520. __decorate([
  70521. BABYLON.serialize()
  70522. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  70523. return DefaultRenderingPipeline;
  70524. }(BABYLON.PostProcessRenderPipeline));
  70525. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  70526. })(BABYLON || (BABYLON = {}));
  70527. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  70528. var BABYLON;
  70529. (function (BABYLON) {
  70530. /**
  70531. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  70532. */
  70533. var GeometryBufferRenderer = /** @class */ (function () {
  70534. /**
  70535. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  70536. * @param scene The scene the buffer belongs to
  70537. * @param ratio How big is the buffer related to the main canvas.
  70538. */
  70539. function GeometryBufferRenderer(scene, ratio) {
  70540. if (ratio === void 0) { ratio = 1; }
  70541. this._enablePosition = false;
  70542. this._scene = scene;
  70543. this._ratio = ratio;
  70544. // Render target
  70545. this._createRenderTargets();
  70546. }
  70547. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  70548. /**
  70549. * Set the render list (meshes to be rendered) used in the G buffer.
  70550. */
  70551. set: function (meshes) {
  70552. this._multiRenderTarget.renderList = meshes;
  70553. },
  70554. enumerable: true,
  70555. configurable: true
  70556. });
  70557. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  70558. /**
  70559. * Gets wether or not G buffer are supported by the running hardware.
  70560. * This requires draw buffer supports
  70561. */
  70562. get: function () {
  70563. return this._multiRenderTarget.isSupported;
  70564. },
  70565. enumerable: true,
  70566. configurable: true
  70567. });
  70568. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  70569. /**
  70570. * Gets wether or not position are enabled for the G buffer.
  70571. */
  70572. get: function () {
  70573. return this._enablePosition;
  70574. },
  70575. /**
  70576. * Sets wether or not position are enabled for the G buffer.
  70577. */
  70578. set: function (enable) {
  70579. this._enablePosition = enable;
  70580. this.dispose();
  70581. this._createRenderTargets();
  70582. },
  70583. enumerable: true,
  70584. configurable: true
  70585. });
  70586. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  70587. /**
  70588. * Gets the scene associated with the buffer.
  70589. */
  70590. get: function () {
  70591. return this._scene;
  70592. },
  70593. enumerable: true,
  70594. configurable: true
  70595. });
  70596. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  70597. /**
  70598. * Gets the ratio used by the buffer during its creation.
  70599. * How big is the buffer related to the main canvas.
  70600. */
  70601. get: function () {
  70602. return this._ratio;
  70603. },
  70604. enumerable: true,
  70605. configurable: true
  70606. });
  70607. /**
  70608. * Checks wether everything is ready to render a submesh to the G buffer.
  70609. * @param subMesh the submesh to check readiness for
  70610. * @param useInstances is the mesh drawn using instance or not
  70611. * @returns true if ready otherwise false
  70612. */
  70613. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  70614. var material = subMesh.getMaterial();
  70615. if (material && material.disableDepthWrite) {
  70616. return false;
  70617. }
  70618. var defines = [];
  70619. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  70620. var mesh = subMesh.getMesh();
  70621. // Alpha test
  70622. if (material && material.needAlphaTesting()) {
  70623. defines.push("#define ALPHATEST");
  70624. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70625. attribs.push(BABYLON.VertexBuffer.UVKind);
  70626. defines.push("#define UV1");
  70627. }
  70628. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  70629. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70630. defines.push("#define UV2");
  70631. }
  70632. }
  70633. // Buffers
  70634. if (this._enablePosition) {
  70635. defines.push("#define POSITION");
  70636. }
  70637. // Bones
  70638. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70639. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70640. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70641. if (mesh.numBoneInfluencers > 4) {
  70642. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  70643. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  70644. }
  70645. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  70646. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  70647. }
  70648. else {
  70649. defines.push("#define NUM_BONE_INFLUENCERS 0");
  70650. }
  70651. // Instances
  70652. if (useInstances) {
  70653. defines.push("#define INSTANCES");
  70654. attribs.push("world0");
  70655. attribs.push("world1");
  70656. attribs.push("world2");
  70657. attribs.push("world3");
  70658. }
  70659. // Get correct effect
  70660. var join = defines.join("\n");
  70661. if (this._cachedDefines !== join) {
  70662. this._cachedDefines = join;
  70663. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  70664. }
  70665. return this._effect.isReady();
  70666. };
  70667. /**
  70668. * Gets the current underlying G Buffer.
  70669. * @returns the buffer
  70670. */
  70671. GeometryBufferRenderer.prototype.getGBuffer = function () {
  70672. return this._multiRenderTarget;
  70673. };
  70674. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  70675. /**
  70676. * Gets the number of samples used to render the buffer (anti aliasing).
  70677. */
  70678. get: function () {
  70679. return this._multiRenderTarget.samples;
  70680. },
  70681. /**
  70682. * Sets the number of samples used to render the buffer (anti aliasing).
  70683. */
  70684. set: function (value) {
  70685. this._multiRenderTarget.samples = value;
  70686. },
  70687. enumerable: true,
  70688. configurable: true
  70689. });
  70690. /**
  70691. * Disposes the renderer and frees up associated resources.
  70692. */
  70693. GeometryBufferRenderer.prototype.dispose = function () {
  70694. this.getGBuffer().dispose();
  70695. };
  70696. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  70697. var _this = this;
  70698. var engine = this._scene.getEngine();
  70699. var count = this._enablePosition ? 3 : 2;
  70700. 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 });
  70701. if (!this.isSupported) {
  70702. return;
  70703. }
  70704. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70705. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70706. this._multiRenderTarget.refreshRate = 1;
  70707. this._multiRenderTarget.renderParticles = false;
  70708. this._multiRenderTarget.renderList = null;
  70709. // set default depth value to 1.0 (far away)
  70710. this._multiRenderTarget.onClearObservable.add(function (engine) {
  70711. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  70712. });
  70713. // Custom render function
  70714. var renderSubMesh = function (subMesh) {
  70715. var mesh = subMesh.getRenderingMesh();
  70716. var scene = _this._scene;
  70717. var engine = scene.getEngine();
  70718. var material = subMesh.getMaterial();
  70719. if (!material) {
  70720. return;
  70721. }
  70722. // Culling
  70723. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  70724. // Managing instances
  70725. var batch = mesh._getInstancesRenderList(subMesh._id);
  70726. if (batch.mustReturn) {
  70727. return;
  70728. }
  70729. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  70730. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  70731. engine.enableEffect(_this._effect);
  70732. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  70733. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  70734. _this._effect.setMatrix("view", scene.getViewMatrix());
  70735. // Alpha test
  70736. if (material && material.needAlphaTesting()) {
  70737. var alphaTexture = material.getAlphaTestTexture();
  70738. if (alphaTexture) {
  70739. _this._effect.setTexture("diffuseSampler", alphaTexture);
  70740. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  70741. }
  70742. }
  70743. // Bones
  70744. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  70745. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  70746. }
  70747. // Draw
  70748. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  70749. }
  70750. };
  70751. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  70752. var index;
  70753. if (depthOnlySubMeshes.length) {
  70754. engine.setColorWrite(false);
  70755. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  70756. renderSubMesh(depthOnlySubMeshes.data[index]);
  70757. }
  70758. engine.setColorWrite(true);
  70759. }
  70760. for (index = 0; index < opaqueSubMeshes.length; index++) {
  70761. renderSubMesh(opaqueSubMeshes.data[index]);
  70762. }
  70763. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  70764. renderSubMesh(alphaTestSubMeshes.data[index]);
  70765. }
  70766. };
  70767. };
  70768. return GeometryBufferRenderer;
  70769. }());
  70770. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  70771. })(BABYLON || (BABYLON = {}));
  70772. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  70773. var BABYLON;
  70774. (function (BABYLON) {
  70775. var RefractionPostProcess = /** @class */ (function (_super) {
  70776. __extends(RefractionPostProcess, _super);
  70777. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  70778. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  70779. _this.color = color;
  70780. _this.depth = depth;
  70781. _this.colorLevel = colorLevel;
  70782. _this._ownRefractionTexture = true;
  70783. _this.onActivateObservable.add(function (cam) {
  70784. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  70785. });
  70786. _this.onApplyObservable.add(function (effect) {
  70787. effect.setColor3("baseColor", _this.color);
  70788. effect.setFloat("depth", _this.depth);
  70789. effect.setFloat("colorLevel", _this.colorLevel);
  70790. effect.setTexture("refractionSampler", _this._refTexture);
  70791. });
  70792. return _this;
  70793. }
  70794. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  70795. /**
  70796. * Gets or sets the refraction texture
  70797. * Please note that you are responsible for disposing the texture if you set it manually
  70798. */
  70799. get: function () {
  70800. return this._refTexture;
  70801. },
  70802. set: function (value) {
  70803. if (this._refTexture && this._ownRefractionTexture) {
  70804. this._refTexture.dispose();
  70805. }
  70806. this._refTexture = value;
  70807. this._ownRefractionTexture = false;
  70808. },
  70809. enumerable: true,
  70810. configurable: true
  70811. });
  70812. // Methods
  70813. RefractionPostProcess.prototype.dispose = function (camera) {
  70814. if (this._refTexture && this._ownRefractionTexture) {
  70815. this._refTexture.dispose();
  70816. this._refTexture = null;
  70817. }
  70818. _super.prototype.dispose.call(this, camera);
  70819. };
  70820. return RefractionPostProcess;
  70821. }(BABYLON.PostProcess));
  70822. BABYLON.RefractionPostProcess = RefractionPostProcess;
  70823. })(BABYLON || (BABYLON = {}));
  70824. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  70825. var BABYLON;
  70826. (function (BABYLON) {
  70827. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  70828. __extends(BlackAndWhitePostProcess, _super);
  70829. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  70830. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  70831. _this.degree = 1;
  70832. _this.onApplyObservable.add(function (effect) {
  70833. effect.setFloat("degree", _this.degree);
  70834. });
  70835. return _this;
  70836. }
  70837. return BlackAndWhitePostProcess;
  70838. }(BABYLON.PostProcess));
  70839. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  70840. })(BABYLON || (BABYLON = {}));
  70841. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  70842. var BABYLON;
  70843. (function (BABYLON) {
  70844. /**
  70845. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  70846. * input texture to perform effects such as edge detection or sharpening
  70847. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  70848. */
  70849. var ConvolutionPostProcess = /** @class */ (function (_super) {
  70850. __extends(ConvolutionPostProcess, _super);
  70851. /**
  70852. * Creates a new instance of @see ConvolutionPostProcess
  70853. * @param name The name of the effect.
  70854. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  70855. * @param options The required width/height ratio to downsize to before computing the render pass.
  70856. * @param camera The camera to apply the render pass to.
  70857. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70858. * @param engine The engine which the post process will be applied. (default: current engine)
  70859. * @param reusable If the post process can be reused on the same frame. (default: false)
  70860. * @param textureType Type of textures used when performing the post process. (default: 0)
  70861. */
  70862. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  70863. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70864. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  70865. _this.kernel = kernel;
  70866. _this.onApply = function (effect) {
  70867. effect.setFloat2("screenSize", _this.width, _this.height);
  70868. effect.setArray("kernel", _this.kernel);
  70869. };
  70870. return _this;
  70871. }
  70872. // Statics
  70873. /**
  70874. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70875. */
  70876. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  70877. /**
  70878. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70879. */
  70880. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  70881. /**
  70882. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70883. */
  70884. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  70885. /**
  70886. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70887. */
  70888. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  70889. /**
  70890. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70891. */
  70892. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  70893. /**
  70894. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70895. */
  70896. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  70897. return ConvolutionPostProcess;
  70898. }(BABYLON.PostProcess));
  70899. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  70900. })(BABYLON || (BABYLON = {}));
  70901. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  70902. var BABYLON;
  70903. (function (BABYLON) {
  70904. var FilterPostProcess = /** @class */ (function (_super) {
  70905. __extends(FilterPostProcess, _super);
  70906. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  70907. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  70908. _this.kernelMatrix = kernelMatrix;
  70909. _this.onApply = function (effect) {
  70910. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  70911. };
  70912. return _this;
  70913. }
  70914. return FilterPostProcess;
  70915. }(BABYLON.PostProcess));
  70916. BABYLON.FilterPostProcess = FilterPostProcess;
  70917. })(BABYLON || (BABYLON = {}));
  70918. //# sourceMappingURL=babylon.filterPostProcess.js.map
  70919. var BABYLON;
  70920. (function (BABYLON) {
  70921. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  70922. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  70923. __extends(VolumetricLightScatteringPostProcess, _super);
  70924. /**
  70925. * @constructor
  70926. * @param {string} name - The post-process name
  70927. * @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)
  70928. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  70929. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  70930. * @param {number} samples - The post-process quality, default 100
  70931. * @param {number} samplingMode - The post-process filtering mode
  70932. * @param {BABYLON.Engine} engine - The babylon engine
  70933. * @param {boolean} reusable - If the post-process is reusable
  70934. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  70935. */
  70936. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  70937. if (samples === void 0) { samples = 100; }
  70938. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70939. 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;
  70940. _this._screenCoordinates = BABYLON.Vector2.Zero();
  70941. /**
  70942. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  70943. * @type {Vector3}
  70944. */
  70945. _this.customMeshPosition = BABYLON.Vector3.Zero();
  70946. /**
  70947. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  70948. * @type {boolean}
  70949. */
  70950. _this.useCustomMeshPosition = false;
  70951. /**
  70952. * If the post-process should inverse the light scattering direction
  70953. * @type {boolean}
  70954. */
  70955. _this.invert = true;
  70956. /**
  70957. * Array containing the excluded meshes not rendered in the internal pass
  70958. */
  70959. _this.excludedMeshes = new Array();
  70960. /**
  70961. * Controls the overall intensity of the post-process
  70962. * @type {number}
  70963. */
  70964. _this.exposure = 0.3;
  70965. /**
  70966. * Dissipates each sample's contribution in range [0, 1]
  70967. * @type {number}
  70968. */
  70969. _this.decay = 0.96815;
  70970. /**
  70971. * Controls the overall intensity of each sample
  70972. * @type {number}
  70973. */
  70974. _this.weight = 0.58767;
  70975. /**
  70976. * Controls the density of each sample
  70977. * @type {number}
  70978. */
  70979. _this.density = 0.926;
  70980. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  70981. engine = scene.getEngine();
  70982. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  70983. // Configure mesh
  70984. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  70985. // Configure
  70986. _this._createPass(scene, ratio.passRatio || ratio);
  70987. _this.onActivate = function (camera) {
  70988. if (!_this.isSupported) {
  70989. _this.dispose(camera);
  70990. }
  70991. _this.onActivate = null;
  70992. };
  70993. _this.onApplyObservable.add(function (effect) {
  70994. _this._updateMeshScreenCoordinates(scene);
  70995. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  70996. effect.setFloat("exposure", _this.exposure);
  70997. effect.setFloat("decay", _this.decay);
  70998. effect.setFloat("weight", _this.weight);
  70999. effect.setFloat("density", _this.density);
  71000. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  71001. });
  71002. return _this;
  71003. }
  71004. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  71005. get: function () {
  71006. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  71007. return false;
  71008. },
  71009. set: function (useDiffuseColor) {
  71010. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  71011. },
  71012. enumerable: true,
  71013. configurable: true
  71014. });
  71015. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  71016. return "VolumetricLightScatteringPostProcess";
  71017. };
  71018. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  71019. var mesh = subMesh.getMesh();
  71020. // Render this.mesh as default
  71021. if (mesh === this.mesh && mesh.material) {
  71022. return mesh.material.isReady(mesh);
  71023. }
  71024. var defines = [];
  71025. var attribs = [BABYLON.VertexBuffer.PositionKind];
  71026. var material = subMesh.getMaterial();
  71027. // Alpha test
  71028. if (material) {
  71029. if (material.needAlphaTesting()) {
  71030. defines.push("#define ALPHATEST");
  71031. }
  71032. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71033. attribs.push(BABYLON.VertexBuffer.UVKind);
  71034. defines.push("#define UV1");
  71035. }
  71036. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71037. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71038. defines.push("#define UV2");
  71039. }
  71040. }
  71041. // Bones
  71042. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71043. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71044. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71045. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71046. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  71047. }
  71048. else {
  71049. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71050. }
  71051. // Instances
  71052. if (useInstances) {
  71053. defines.push("#define INSTANCES");
  71054. attribs.push("world0");
  71055. attribs.push("world1");
  71056. attribs.push("world2");
  71057. attribs.push("world3");
  71058. }
  71059. // Get correct effect
  71060. var join = defines.join("\n");
  71061. if (this._cachedDefines !== join) {
  71062. this._cachedDefines = join;
  71063. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  71064. }
  71065. return this._volumetricLightScatteringPass.isReady();
  71066. };
  71067. /**
  71068. * Sets the new light position for light scattering effect
  71069. * @param {BABYLON.Vector3} The new custom light position
  71070. */
  71071. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  71072. this.customMeshPosition = position;
  71073. };
  71074. /**
  71075. * Returns the light position for light scattering effect
  71076. * @return {BABYLON.Vector3} The custom light position
  71077. */
  71078. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  71079. return this.customMeshPosition;
  71080. };
  71081. /**
  71082. * Disposes the internal assets and detaches the post-process from the camera
  71083. */
  71084. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  71085. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  71086. if (rttIndex !== -1) {
  71087. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  71088. }
  71089. this._volumetricLightScatteringRTT.dispose();
  71090. _super.prototype.dispose.call(this, camera);
  71091. };
  71092. /**
  71093. * Returns the render target texture used by the post-process
  71094. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  71095. */
  71096. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  71097. return this._volumetricLightScatteringRTT;
  71098. };
  71099. // Private methods
  71100. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  71101. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  71102. return true;
  71103. }
  71104. return false;
  71105. };
  71106. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  71107. var _this = this;
  71108. var engine = scene.getEngine();
  71109. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  71110. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71111. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71112. this._volumetricLightScatteringRTT.renderList = null;
  71113. this._volumetricLightScatteringRTT.renderParticles = false;
  71114. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  71115. var camera = this.getCamera();
  71116. if (camera) {
  71117. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  71118. }
  71119. else {
  71120. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  71121. }
  71122. // Custom render function for submeshes
  71123. var renderSubMesh = function (subMesh) {
  71124. var mesh = subMesh.getRenderingMesh();
  71125. if (_this._meshExcluded(mesh)) {
  71126. return;
  71127. }
  71128. var material = subMesh.getMaterial();
  71129. if (!material) {
  71130. return;
  71131. }
  71132. var scene = mesh.getScene();
  71133. var engine = scene.getEngine();
  71134. // Culling
  71135. engine.setState(material.backFaceCulling);
  71136. // Managing instances
  71137. var batch = mesh._getInstancesRenderList(subMesh._id);
  71138. if (batch.mustReturn) {
  71139. return;
  71140. }
  71141. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  71142. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  71143. var effect = _this._volumetricLightScatteringPass;
  71144. if (mesh === _this.mesh) {
  71145. if (subMesh.effect) {
  71146. effect = subMesh.effect;
  71147. }
  71148. else {
  71149. effect = material.getEffect();
  71150. }
  71151. }
  71152. engine.enableEffect(effect);
  71153. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  71154. if (mesh === _this.mesh) {
  71155. material.bind(mesh.getWorldMatrix(), mesh);
  71156. }
  71157. else {
  71158. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  71159. // Alpha test
  71160. if (material && material.needAlphaTesting()) {
  71161. var alphaTexture = material.getAlphaTestTexture();
  71162. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  71163. if (alphaTexture) {
  71164. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71165. }
  71166. }
  71167. // Bones
  71168. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71169. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71170. }
  71171. }
  71172. // Draw
  71173. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  71174. }
  71175. };
  71176. // Render target texture callbacks
  71177. var savedSceneClearColor;
  71178. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  71179. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  71180. savedSceneClearColor = scene.clearColor;
  71181. scene.clearColor = sceneClearColor;
  71182. });
  71183. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  71184. scene.clearColor = savedSceneClearColor;
  71185. });
  71186. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  71187. var engine = scene.getEngine();
  71188. var index;
  71189. if (depthOnlySubMeshes.length) {
  71190. engine.setColorWrite(false);
  71191. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  71192. renderSubMesh(depthOnlySubMeshes.data[index]);
  71193. }
  71194. engine.setColorWrite(true);
  71195. }
  71196. for (index = 0; index < opaqueSubMeshes.length; index++) {
  71197. renderSubMesh(opaqueSubMeshes.data[index]);
  71198. }
  71199. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  71200. renderSubMesh(alphaTestSubMeshes.data[index]);
  71201. }
  71202. if (transparentSubMeshes.length) {
  71203. // Sort sub meshes
  71204. for (index = 0; index < transparentSubMeshes.length; index++) {
  71205. var submesh = transparentSubMeshes.data[index];
  71206. var boundingInfo = submesh.getBoundingInfo();
  71207. if (boundingInfo && scene.activeCamera) {
  71208. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  71209. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  71210. }
  71211. }
  71212. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  71213. sortedArray.sort(function (a, b) {
  71214. // Alpha index first
  71215. if (a._alphaIndex > b._alphaIndex) {
  71216. return 1;
  71217. }
  71218. if (a._alphaIndex < b._alphaIndex) {
  71219. return -1;
  71220. }
  71221. // Then distance to camera
  71222. if (a._distanceToCamera < b._distanceToCamera) {
  71223. return 1;
  71224. }
  71225. if (a._distanceToCamera > b._distanceToCamera) {
  71226. return -1;
  71227. }
  71228. return 0;
  71229. });
  71230. // Render sub meshes
  71231. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  71232. for (index = 0; index < sortedArray.length; index++) {
  71233. renderSubMesh(sortedArray[index]);
  71234. }
  71235. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  71236. }
  71237. };
  71238. };
  71239. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  71240. var transform = scene.getTransformMatrix();
  71241. var meshPosition;
  71242. if (this.useCustomMeshPosition) {
  71243. meshPosition = this.customMeshPosition;
  71244. }
  71245. else if (this.attachedNode) {
  71246. meshPosition = this.attachedNode.position;
  71247. }
  71248. else {
  71249. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  71250. }
  71251. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  71252. this._screenCoordinates.x = pos.x / this._viewPort.width;
  71253. this._screenCoordinates.y = pos.y / this._viewPort.height;
  71254. if (this.invert)
  71255. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  71256. };
  71257. // Static methods
  71258. /**
  71259. * Creates a default mesh for the Volumeric Light Scattering post-process
  71260. * @param {string} The mesh name
  71261. * @param {BABYLON.Scene} The scene where to create the mesh
  71262. * @return {BABYLON.Mesh} the default mesh
  71263. */
  71264. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  71265. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  71266. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  71267. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  71268. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  71269. mesh.material = material;
  71270. return mesh;
  71271. };
  71272. __decorate([
  71273. BABYLON.serializeAsVector3()
  71274. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  71275. __decorate([
  71276. BABYLON.serialize()
  71277. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  71278. __decorate([
  71279. BABYLON.serialize()
  71280. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  71281. __decorate([
  71282. BABYLON.serializeAsMeshReference()
  71283. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  71284. __decorate([
  71285. BABYLON.serialize()
  71286. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  71287. __decorate([
  71288. BABYLON.serialize()
  71289. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  71290. __decorate([
  71291. BABYLON.serialize()
  71292. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  71293. __decorate([
  71294. BABYLON.serialize()
  71295. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  71296. __decorate([
  71297. BABYLON.serialize()
  71298. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  71299. return VolumetricLightScatteringPostProcess;
  71300. }(BABYLON.PostProcess));
  71301. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  71302. })(BABYLON || (BABYLON = {}));
  71303. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  71304. //
  71305. // This post-process allows the modification of rendered colors by using
  71306. // a 'look-up table' (LUT). This effect is also called Color Grading.
  71307. //
  71308. // The object needs to be provided an url to a texture containing the color
  71309. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  71310. // Use an image editing software to tweak the LUT to match your needs.
  71311. //
  71312. // For an example of a color LUT, see here:
  71313. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  71314. // For explanations on color grading, see here:
  71315. // http://udn.epicgames.com/Three/ColorGrading.html
  71316. //
  71317. var BABYLON;
  71318. (function (BABYLON) {
  71319. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  71320. __extends(ColorCorrectionPostProcess, _super);
  71321. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  71322. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  71323. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  71324. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  71325. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71326. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71327. _this.onApply = function (effect) {
  71328. effect.setTexture("colorTable", _this._colorTableTexture);
  71329. };
  71330. return _this;
  71331. }
  71332. return ColorCorrectionPostProcess;
  71333. }(BABYLON.PostProcess));
  71334. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  71335. })(BABYLON || (BABYLON = {}));
  71336. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  71337. var BABYLON;
  71338. (function (BABYLON) {
  71339. var TonemappingOperator;
  71340. (function (TonemappingOperator) {
  71341. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  71342. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  71343. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  71344. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  71345. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  71346. ;
  71347. var TonemapPostProcess = /** @class */ (function (_super) {
  71348. __extends(TonemapPostProcess, _super);
  71349. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  71350. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71351. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71352. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  71353. _this._operator = _operator;
  71354. _this.exposureAdjustment = exposureAdjustment;
  71355. var defines = "#define ";
  71356. if (_this._operator === TonemappingOperator.Hable)
  71357. defines += "HABLE_TONEMAPPING";
  71358. else if (_this._operator === TonemappingOperator.Reinhard)
  71359. defines += "REINHARD_TONEMAPPING";
  71360. else if (_this._operator === TonemappingOperator.HejiDawson)
  71361. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  71362. else if (_this._operator === TonemappingOperator.Photographic)
  71363. defines += "PHOTOGRAPHIC_TONEMAPPING";
  71364. //sadly a second call to create the effect.
  71365. _this.updateEffect(defines);
  71366. _this.onApply = function (effect) {
  71367. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  71368. };
  71369. return _this;
  71370. }
  71371. return TonemapPostProcess;
  71372. }(BABYLON.PostProcess));
  71373. BABYLON.TonemapPostProcess = TonemapPostProcess;
  71374. })(BABYLON || (BABYLON = {}));
  71375. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  71376. var BABYLON;
  71377. (function (BABYLON) {
  71378. var DisplayPassPostProcess = /** @class */ (function (_super) {
  71379. __extends(DisplayPassPostProcess, _super);
  71380. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  71381. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  71382. }
  71383. return DisplayPassPostProcess;
  71384. }(BABYLON.PostProcess));
  71385. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  71386. })(BABYLON || (BABYLON = {}));
  71387. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  71388. var BABYLON;
  71389. (function (BABYLON) {
  71390. var HighlightsPostProcess = /** @class */ (function (_super) {
  71391. __extends(HighlightsPostProcess, _super);
  71392. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  71393. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71394. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  71395. }
  71396. return HighlightsPostProcess;
  71397. }(BABYLON.PostProcess));
  71398. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  71399. })(BABYLON || (BABYLON = {}));
  71400. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  71401. var BABYLON;
  71402. (function (BABYLON) {
  71403. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  71404. __extends(ImageProcessingPostProcess, _super);
  71405. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  71406. if (camera === void 0) { camera = null; }
  71407. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71408. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  71409. _this._fromLinearSpace = true;
  71410. /**
  71411. * Defines cache preventing GC.
  71412. */
  71413. _this._defines = {
  71414. IMAGEPROCESSING: false,
  71415. VIGNETTE: false,
  71416. VIGNETTEBLENDMODEMULTIPLY: false,
  71417. VIGNETTEBLENDMODEOPAQUE: false,
  71418. TONEMAPPING: false,
  71419. CONTRAST: false,
  71420. COLORCURVES: false,
  71421. COLORGRADING: false,
  71422. COLORGRADING3D: false,
  71423. FROMLINEARSPACE: false,
  71424. SAMPLER3DGREENDEPTH: false,
  71425. SAMPLER3DBGRMAP: false,
  71426. IMAGEPROCESSINGPOSTPROCESS: false,
  71427. EXPOSURE: false,
  71428. GRAIN: false,
  71429. };
  71430. // Setup the configuration as forced by the constructor. This would then not force the
  71431. // scene materials output in linear space and let untouched the default forward pass.
  71432. if (imageProcessingConfiguration) {
  71433. imageProcessingConfiguration.applyByPostProcess = true;
  71434. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  71435. // This will cause the shader to be compiled
  71436. _this.fromLinearSpace = false;
  71437. }
  71438. else {
  71439. _this._attachImageProcessingConfiguration(null, true);
  71440. _this.imageProcessingConfiguration.applyByPostProcess = true;
  71441. }
  71442. _this.onApply = function (effect) {
  71443. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  71444. };
  71445. return _this;
  71446. }
  71447. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  71448. /**
  71449. * Gets the image processing configuration used either in this material.
  71450. */
  71451. get: function () {
  71452. return this._imageProcessingConfiguration;
  71453. },
  71454. /**
  71455. * Sets the Default image processing configuration used either in the this material.
  71456. *
  71457. * If sets to null, the scene one is in use.
  71458. */
  71459. set: function (value) {
  71460. this._attachImageProcessingConfiguration(value);
  71461. },
  71462. enumerable: true,
  71463. configurable: true
  71464. });
  71465. /**
  71466. * Attaches a new image processing configuration to the PBR Material.
  71467. * @param configuration
  71468. */
  71469. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  71470. var _this = this;
  71471. if (doNotBuild === void 0) { doNotBuild = false; }
  71472. if (configuration === this._imageProcessingConfiguration) {
  71473. return;
  71474. }
  71475. // Detaches observer.
  71476. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  71477. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  71478. }
  71479. // Pick the scene configuration if needed.
  71480. if (!configuration) {
  71481. var scene = null;
  71482. var engine = this.getEngine();
  71483. var camera = this.getCamera();
  71484. if (camera) {
  71485. scene = camera.getScene();
  71486. }
  71487. else if (engine && engine.scenes) {
  71488. var scenes = engine.scenes;
  71489. scene = scenes[scenes.length - 1];
  71490. }
  71491. else {
  71492. scene = BABYLON.Engine.LastCreatedScene;
  71493. }
  71494. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  71495. }
  71496. else {
  71497. this._imageProcessingConfiguration = configuration;
  71498. }
  71499. // Attaches observer.
  71500. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  71501. _this._updateParameters();
  71502. });
  71503. // Ensure the effect will be rebuilt.
  71504. if (!doNotBuild) {
  71505. this._updateParameters();
  71506. }
  71507. };
  71508. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  71509. /**
  71510. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  71511. */
  71512. get: function () {
  71513. return this.imageProcessingConfiguration.colorCurves;
  71514. },
  71515. /**
  71516. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  71517. */
  71518. set: function (value) {
  71519. this.imageProcessingConfiguration.colorCurves = value;
  71520. },
  71521. enumerable: true,
  71522. configurable: true
  71523. });
  71524. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  71525. /**
  71526. * Gets wether the color curves effect is enabled.
  71527. */
  71528. get: function () {
  71529. return this.imageProcessingConfiguration.colorCurvesEnabled;
  71530. },
  71531. /**
  71532. * Sets wether the color curves effect is enabled.
  71533. */
  71534. set: function (value) {
  71535. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  71536. },
  71537. enumerable: true,
  71538. configurable: true
  71539. });
  71540. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  71541. /**
  71542. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  71543. */
  71544. get: function () {
  71545. return this.imageProcessingConfiguration.colorGradingTexture;
  71546. },
  71547. /**
  71548. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  71549. */
  71550. set: function (value) {
  71551. this.imageProcessingConfiguration.colorGradingTexture = value;
  71552. },
  71553. enumerable: true,
  71554. configurable: true
  71555. });
  71556. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  71557. /**
  71558. * Gets wether the color grading effect is enabled.
  71559. */
  71560. get: function () {
  71561. return this.imageProcessingConfiguration.colorGradingEnabled;
  71562. },
  71563. /**
  71564. * Gets wether the color grading effect is enabled.
  71565. */
  71566. set: function (value) {
  71567. this.imageProcessingConfiguration.colorGradingEnabled = value;
  71568. },
  71569. enumerable: true,
  71570. configurable: true
  71571. });
  71572. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  71573. /**
  71574. * Gets exposure used in the effect.
  71575. */
  71576. get: function () {
  71577. return this.imageProcessingConfiguration.exposure;
  71578. },
  71579. /**
  71580. * Sets exposure used in the effect.
  71581. */
  71582. set: function (value) {
  71583. this.imageProcessingConfiguration.exposure = value;
  71584. },
  71585. enumerable: true,
  71586. configurable: true
  71587. });
  71588. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  71589. /**
  71590. * Gets wether tonemapping is enabled or not.
  71591. */
  71592. get: function () {
  71593. return this._imageProcessingConfiguration.toneMappingEnabled;
  71594. },
  71595. /**
  71596. * Sets wether tonemapping is enabled or not
  71597. */
  71598. set: function (value) {
  71599. this._imageProcessingConfiguration.toneMappingEnabled = value;
  71600. },
  71601. enumerable: true,
  71602. configurable: true
  71603. });
  71604. ;
  71605. ;
  71606. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  71607. /**
  71608. * Gets contrast used in the effect.
  71609. */
  71610. get: function () {
  71611. return this.imageProcessingConfiguration.contrast;
  71612. },
  71613. /**
  71614. * Sets contrast used in the effect.
  71615. */
  71616. set: function (value) {
  71617. this.imageProcessingConfiguration.contrast = value;
  71618. },
  71619. enumerable: true,
  71620. configurable: true
  71621. });
  71622. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  71623. /**
  71624. * Gets Vignette stretch size.
  71625. */
  71626. get: function () {
  71627. return this.imageProcessingConfiguration.vignetteStretch;
  71628. },
  71629. /**
  71630. * Sets Vignette stretch size.
  71631. */
  71632. set: function (value) {
  71633. this.imageProcessingConfiguration.vignetteStretch = value;
  71634. },
  71635. enumerable: true,
  71636. configurable: true
  71637. });
  71638. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  71639. /**
  71640. * Gets Vignette centre X Offset.
  71641. */
  71642. get: function () {
  71643. return this.imageProcessingConfiguration.vignetteCentreX;
  71644. },
  71645. /**
  71646. * Sets Vignette centre X Offset.
  71647. */
  71648. set: function (value) {
  71649. this.imageProcessingConfiguration.vignetteCentreX = value;
  71650. },
  71651. enumerable: true,
  71652. configurable: true
  71653. });
  71654. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  71655. /**
  71656. * Gets Vignette centre Y Offset.
  71657. */
  71658. get: function () {
  71659. return this.imageProcessingConfiguration.vignetteCentreY;
  71660. },
  71661. /**
  71662. * Sets Vignette centre Y Offset.
  71663. */
  71664. set: function (value) {
  71665. this.imageProcessingConfiguration.vignetteCentreY = value;
  71666. },
  71667. enumerable: true,
  71668. configurable: true
  71669. });
  71670. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  71671. /**
  71672. * Gets Vignette weight or intensity of the vignette effect.
  71673. */
  71674. get: function () {
  71675. return this.imageProcessingConfiguration.vignetteWeight;
  71676. },
  71677. /**
  71678. * Sets Vignette weight or intensity of the vignette effect.
  71679. */
  71680. set: function (value) {
  71681. this.imageProcessingConfiguration.vignetteWeight = value;
  71682. },
  71683. enumerable: true,
  71684. configurable: true
  71685. });
  71686. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  71687. /**
  71688. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  71689. * if vignetteEnabled is set to true.
  71690. */
  71691. get: function () {
  71692. return this.imageProcessingConfiguration.vignetteColor;
  71693. },
  71694. /**
  71695. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  71696. * if vignetteEnabled is set to true.
  71697. */
  71698. set: function (value) {
  71699. this.imageProcessingConfiguration.vignetteColor = value;
  71700. },
  71701. enumerable: true,
  71702. configurable: true
  71703. });
  71704. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  71705. /**
  71706. * Gets Camera field of view used by the Vignette effect.
  71707. */
  71708. get: function () {
  71709. return this.imageProcessingConfiguration.vignetteCameraFov;
  71710. },
  71711. /**
  71712. * Sets Camera field of view used by the Vignette effect.
  71713. */
  71714. set: function (value) {
  71715. this.imageProcessingConfiguration.vignetteCameraFov = value;
  71716. },
  71717. enumerable: true,
  71718. configurable: true
  71719. });
  71720. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  71721. /**
  71722. * Gets the vignette blend mode allowing different kind of effect.
  71723. */
  71724. get: function () {
  71725. return this.imageProcessingConfiguration.vignetteBlendMode;
  71726. },
  71727. /**
  71728. * Sets the vignette blend mode allowing different kind of effect.
  71729. */
  71730. set: function (value) {
  71731. this.imageProcessingConfiguration.vignetteBlendMode = value;
  71732. },
  71733. enumerable: true,
  71734. configurable: true
  71735. });
  71736. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  71737. /**
  71738. * Gets wether the vignette effect is enabled.
  71739. */
  71740. get: function () {
  71741. return this.imageProcessingConfiguration.vignetteEnabled;
  71742. },
  71743. /**
  71744. * Sets wether the vignette effect is enabled.
  71745. */
  71746. set: function (value) {
  71747. this.imageProcessingConfiguration.vignetteEnabled = value;
  71748. },
  71749. enumerable: true,
  71750. configurable: true
  71751. });
  71752. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainEnabled", {
  71753. /**
  71754. * Gets wether the grain effect is enabled.
  71755. */
  71756. get: function () {
  71757. return this.imageProcessingConfiguration.grainEnabled;
  71758. },
  71759. /**
  71760. * Sets wether the grain effect is enabled.
  71761. */
  71762. set: function (value) {
  71763. this.imageProcessingConfiguration.grainEnabled = value;
  71764. },
  71765. enumerable: true,
  71766. configurable: true
  71767. });
  71768. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainIntensity", {
  71769. /**
  71770. * Gets the grain effect's intensity.
  71771. */
  71772. get: function () {
  71773. return this.imageProcessingConfiguration.grainIntensity;
  71774. },
  71775. /**
  71776. * Sets the grain effect's intensity.
  71777. */
  71778. set: function (value) {
  71779. this.imageProcessingConfiguration.grainIntensity = value;
  71780. },
  71781. enumerable: true,
  71782. configurable: true
  71783. });
  71784. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainAnimated", {
  71785. /**
  71786. * Gets wether the grain effect is animated.
  71787. */
  71788. get: function () {
  71789. return this.imageProcessingConfiguration.grainAnimated;
  71790. },
  71791. /**
  71792. * Sets wether the grain effect is animated.
  71793. */
  71794. set: function (value) {
  71795. this.imageProcessingConfiguration.grainAnimated = value;
  71796. },
  71797. enumerable: true,
  71798. configurable: true
  71799. });
  71800. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  71801. /**
  71802. * Gets wether the input of the processing is in Gamma or Linear Space.
  71803. */
  71804. get: function () {
  71805. return this._fromLinearSpace;
  71806. },
  71807. /**
  71808. * Sets wether the input of the processing is in Gamma or Linear Space.
  71809. */
  71810. set: function (value) {
  71811. if (this._fromLinearSpace === value) {
  71812. return;
  71813. }
  71814. this._fromLinearSpace = value;
  71815. this._updateParameters();
  71816. },
  71817. enumerable: true,
  71818. configurable: true
  71819. });
  71820. ImageProcessingPostProcess.prototype.getClassName = function () {
  71821. return "ImageProcessingPostProcess";
  71822. };
  71823. ImageProcessingPostProcess.prototype._updateParameters = function () {
  71824. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  71825. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  71826. var defines = "";
  71827. for (var define in this._defines) {
  71828. if (this._defines[define]) {
  71829. defines += "#define " + define + ";\r\n";
  71830. }
  71831. }
  71832. var samplers = ["textureSampler"];
  71833. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  71834. var uniforms = ["scale"];
  71835. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  71836. this.updateEffect(defines, uniforms, samplers);
  71837. };
  71838. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  71839. _super.prototype.dispose.call(this, camera);
  71840. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  71841. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  71842. }
  71843. this.imageProcessingConfiguration.applyByPostProcess = false;
  71844. };
  71845. __decorate([
  71846. BABYLON.serialize()
  71847. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  71848. return ImageProcessingPostProcess;
  71849. }(BABYLON.PostProcess));
  71850. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  71851. })(BABYLON || (BABYLON = {}));
  71852. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  71853. var BABYLON;
  71854. (function (BABYLON) {
  71855. var Bone = /** @class */ (function (_super) {
  71856. __extends(Bone, _super);
  71857. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  71858. if (parentBone === void 0) { parentBone = null; }
  71859. if (localMatrix === void 0) { localMatrix = null; }
  71860. if (restPose === void 0) { restPose = null; }
  71861. if (baseMatrix === void 0) { baseMatrix = null; }
  71862. if (index === void 0) { index = null; }
  71863. var _this = _super.call(this, name, skeleton.getScene()) || this;
  71864. _this.name = name;
  71865. _this.children = new Array();
  71866. _this.animations = new Array();
  71867. // Set this value to map this bone to a different index in the transform matrices.
  71868. // Set this value to -1 to exclude the bone from the transform matrices.
  71869. _this._index = null;
  71870. _this._worldTransform = new BABYLON.Matrix();
  71871. _this._absoluteTransform = new BABYLON.Matrix();
  71872. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  71873. _this._scaleMatrix = BABYLON.Matrix.Identity();
  71874. _this._scaleVector = BABYLON.Vector3.One();
  71875. _this._negateScaleChildren = BABYLON.Vector3.One();
  71876. _this._scalingDeterminant = 1;
  71877. _this._skeleton = skeleton;
  71878. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  71879. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  71880. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  71881. _this._index = index;
  71882. skeleton.bones.push(_this);
  71883. _this.setParent(parentBone, false);
  71884. _this._updateDifferenceMatrix();
  71885. return _this;
  71886. }
  71887. Object.defineProperty(Bone.prototype, "_matrix", {
  71888. get: function () {
  71889. return this._localMatrix;
  71890. },
  71891. set: function (val) {
  71892. if (this._localMatrix) {
  71893. this._localMatrix.copyFrom(val);
  71894. }
  71895. else {
  71896. this._localMatrix = val;
  71897. }
  71898. },
  71899. enumerable: true,
  71900. configurable: true
  71901. });
  71902. // Members
  71903. Bone.prototype.getSkeleton = function () {
  71904. return this._skeleton;
  71905. };
  71906. Bone.prototype.getParent = function () {
  71907. return this._parent;
  71908. };
  71909. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  71910. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  71911. if (this._parent === parent) {
  71912. return;
  71913. }
  71914. if (this._parent) {
  71915. var index = this._parent.children.indexOf(this);
  71916. if (index !== -1) {
  71917. this._parent.children.splice(index, 1);
  71918. }
  71919. }
  71920. this._parent = parent;
  71921. if (this._parent) {
  71922. this._parent.children.push(this);
  71923. }
  71924. if (updateDifferenceMatrix) {
  71925. this._updateDifferenceMatrix();
  71926. }
  71927. };
  71928. Bone.prototype.getLocalMatrix = function () {
  71929. return this._localMatrix;
  71930. };
  71931. Bone.prototype.getBaseMatrix = function () {
  71932. return this._baseMatrix;
  71933. };
  71934. Bone.prototype.getRestPose = function () {
  71935. return this._restPose;
  71936. };
  71937. Bone.prototype.returnToRest = function () {
  71938. this.updateMatrix(this._restPose.clone());
  71939. };
  71940. Bone.prototype.getWorldMatrix = function () {
  71941. return this._worldTransform;
  71942. };
  71943. Bone.prototype.getInvertedAbsoluteTransform = function () {
  71944. return this._invertedAbsoluteTransform;
  71945. };
  71946. Bone.prototype.getAbsoluteTransform = function () {
  71947. return this._absoluteTransform;
  71948. };
  71949. Object.defineProperty(Bone.prototype, "position", {
  71950. // Properties (matches AbstractMesh properties)
  71951. get: function () {
  71952. return this.getPosition();
  71953. },
  71954. set: function (newPosition) {
  71955. this.setPosition(newPosition);
  71956. },
  71957. enumerable: true,
  71958. configurable: true
  71959. });
  71960. Object.defineProperty(Bone.prototype, "rotation", {
  71961. get: function () {
  71962. return this.getRotation();
  71963. },
  71964. set: function (newRotation) {
  71965. this.setRotation(newRotation);
  71966. },
  71967. enumerable: true,
  71968. configurable: true
  71969. });
  71970. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  71971. get: function () {
  71972. return this.getRotationQuaternion();
  71973. },
  71974. set: function (newRotation) {
  71975. this.setRotationQuaternion(newRotation);
  71976. },
  71977. enumerable: true,
  71978. configurable: true
  71979. });
  71980. Object.defineProperty(Bone.prototype, "scaling", {
  71981. get: function () {
  71982. return this.getScale();
  71983. },
  71984. set: function (newScaling) {
  71985. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  71986. },
  71987. enumerable: true,
  71988. configurable: true
  71989. });
  71990. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  71991. /**
  71992. * Gets the animation properties override
  71993. */
  71994. get: function () {
  71995. return this._skeleton.animationPropertiesOverride;
  71996. },
  71997. enumerable: true,
  71998. configurable: true
  71999. });
  72000. // Methods
  72001. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  72002. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  72003. this._baseMatrix = matrix.clone();
  72004. this._localMatrix = matrix.clone();
  72005. this._skeleton._markAsDirty();
  72006. if (updateDifferenceMatrix) {
  72007. this._updateDifferenceMatrix();
  72008. }
  72009. };
  72010. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  72011. if (!rootMatrix) {
  72012. rootMatrix = this._baseMatrix;
  72013. }
  72014. if (this._parent) {
  72015. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  72016. }
  72017. else {
  72018. this._absoluteTransform.copyFrom(rootMatrix);
  72019. }
  72020. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  72021. for (var index = 0; index < this.children.length; index++) {
  72022. this.children[index]._updateDifferenceMatrix();
  72023. }
  72024. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  72025. };
  72026. Bone.prototype.markAsDirty = function () {
  72027. this._currentRenderId++;
  72028. this._skeleton._markAsDirty();
  72029. };
  72030. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  72031. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  72032. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  72033. // all animation may be coming from a library skeleton, so may need to create animation
  72034. if (this.animations.length === 0) {
  72035. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  72036. this.animations[0].setKeys([]);
  72037. }
  72038. // get animation info / verify there is such a range from the source bone
  72039. var sourceRange = source.animations[0].getRange(rangeName);
  72040. if (!sourceRange) {
  72041. return false;
  72042. }
  72043. var from = sourceRange.from;
  72044. var to = sourceRange.to;
  72045. var sourceKeys = source.animations[0].getKeys();
  72046. // rescaling prep
  72047. var sourceBoneLength = source.length;
  72048. var sourceParent = source.getParent();
  72049. var parent = this.getParent();
  72050. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  72051. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  72052. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  72053. var destKeys = this.animations[0].getKeys();
  72054. // loop vars declaration
  72055. var orig;
  72056. var origTranslation;
  72057. var mat;
  72058. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  72059. orig = sourceKeys[key];
  72060. if (orig.frame >= from && orig.frame <= to) {
  72061. if (rescaleAsRequired) {
  72062. mat = orig.value.clone();
  72063. // scale based on parent ratio, when bone has parent
  72064. if (parentScalingReqd) {
  72065. origTranslation = mat.getTranslation();
  72066. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  72067. // scale based on skeleton dimension ratio when root bone, and value is passed
  72068. }
  72069. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  72070. origTranslation = mat.getTranslation();
  72071. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  72072. // use original when root bone, and no data for skelDimensionsRatio
  72073. }
  72074. else {
  72075. mat = orig.value;
  72076. }
  72077. }
  72078. else {
  72079. mat = orig.value;
  72080. }
  72081. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  72082. }
  72083. }
  72084. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  72085. return true;
  72086. };
  72087. /**
  72088. * Translate the bone in local or world space.
  72089. * @param vec The amount to translate the bone.
  72090. * @param space The space that the translation is in.
  72091. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72092. */
  72093. Bone.prototype.translate = function (vec, space, mesh) {
  72094. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72095. var lm = this.getLocalMatrix();
  72096. if (space == BABYLON.Space.LOCAL) {
  72097. lm.m[12] += vec.x;
  72098. lm.m[13] += vec.y;
  72099. lm.m[14] += vec.z;
  72100. }
  72101. else {
  72102. var wm = null;
  72103. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72104. if (mesh) {
  72105. wm = mesh.getWorldMatrix();
  72106. }
  72107. this._skeleton.computeAbsoluteTransforms();
  72108. var tmat = Bone._tmpMats[0];
  72109. var tvec = Bone._tmpVecs[0];
  72110. if (this._parent) {
  72111. if (mesh && wm) {
  72112. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72113. tmat.multiplyToRef(wm, tmat);
  72114. }
  72115. else {
  72116. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72117. }
  72118. }
  72119. tmat.m[12] = 0;
  72120. tmat.m[13] = 0;
  72121. tmat.m[14] = 0;
  72122. tmat.invert();
  72123. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  72124. lm.m[12] += tvec.x;
  72125. lm.m[13] += tvec.y;
  72126. lm.m[14] += tvec.z;
  72127. }
  72128. this.markAsDirty();
  72129. };
  72130. /**
  72131. * Set the postion of the bone in local or world space.
  72132. * @param position The position to set the bone.
  72133. * @param space The space that the position is in.
  72134. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72135. */
  72136. Bone.prototype.setPosition = function (position, space, mesh) {
  72137. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72138. var lm = this.getLocalMatrix();
  72139. if (space == BABYLON.Space.LOCAL) {
  72140. lm.m[12] = position.x;
  72141. lm.m[13] = position.y;
  72142. lm.m[14] = position.z;
  72143. }
  72144. else {
  72145. var wm = null;
  72146. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72147. if (mesh) {
  72148. wm = mesh.getWorldMatrix();
  72149. }
  72150. this._skeleton.computeAbsoluteTransforms();
  72151. var tmat = Bone._tmpMats[0];
  72152. var vec = Bone._tmpVecs[0];
  72153. if (this._parent) {
  72154. if (mesh && wm) {
  72155. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72156. tmat.multiplyToRef(wm, tmat);
  72157. }
  72158. else {
  72159. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72160. }
  72161. }
  72162. tmat.invert();
  72163. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  72164. lm.m[12] = vec.x;
  72165. lm.m[13] = vec.y;
  72166. lm.m[14] = vec.z;
  72167. }
  72168. this.markAsDirty();
  72169. };
  72170. /**
  72171. * Set the absolute postion of the bone (world space).
  72172. * @param position The position to set the bone.
  72173. * @param mesh The mesh that this bone is attached to.
  72174. */
  72175. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  72176. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  72177. };
  72178. /**
  72179. * Set the scale of the bone on the x, y and z axes.
  72180. * @param x The scale of the bone on the x axis.
  72181. * @param x The scale of the bone on the y axis.
  72182. * @param z The scale of the bone on the z axis.
  72183. * @param scaleChildren Set this to true if children of the bone should be scaled.
  72184. */
  72185. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  72186. if (scaleChildren === void 0) { scaleChildren = false; }
  72187. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  72188. if (!scaleChildren) {
  72189. this._negateScaleChildren.x = 1 / x;
  72190. this._negateScaleChildren.y = 1 / y;
  72191. this._negateScaleChildren.z = 1 / z;
  72192. }
  72193. this._syncScaleVector();
  72194. }
  72195. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  72196. };
  72197. /**
  72198. * Scale the bone on the x, y and z axes.
  72199. * @param x The amount to scale the bone on the x axis.
  72200. * @param x The amount to scale the bone on the y axis.
  72201. * @param z The amount to scale the bone on the z axis.
  72202. * @param scaleChildren Set this to true if children of the bone should be scaled.
  72203. */
  72204. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  72205. if (scaleChildren === void 0) { scaleChildren = false; }
  72206. var locMat = this.getLocalMatrix();
  72207. var origLocMat = Bone._tmpMats[0];
  72208. origLocMat.copyFrom(locMat);
  72209. var origLocMatInv = Bone._tmpMats[1];
  72210. origLocMatInv.copyFrom(origLocMat);
  72211. origLocMatInv.invert();
  72212. var scaleMat = Bone._tmpMats[2];
  72213. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  72214. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  72215. this._scaleVector.x *= x;
  72216. this._scaleVector.y *= y;
  72217. this._scaleVector.z *= z;
  72218. locMat.multiplyToRef(origLocMatInv, locMat);
  72219. locMat.multiplyToRef(scaleMat, locMat);
  72220. locMat.multiplyToRef(origLocMat, locMat);
  72221. var parent = this.getParent();
  72222. if (parent) {
  72223. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  72224. }
  72225. else {
  72226. this.getAbsoluteTransform().copyFrom(locMat);
  72227. }
  72228. var len = this.children.length;
  72229. scaleMat.invert();
  72230. for (var i = 0; i < len; i++) {
  72231. var child = this.children[i];
  72232. var cm = child.getLocalMatrix();
  72233. cm.multiplyToRef(scaleMat, cm);
  72234. var lm = child.getLocalMatrix();
  72235. lm.m[12] *= x;
  72236. lm.m[13] *= y;
  72237. lm.m[14] *= z;
  72238. }
  72239. this.computeAbsoluteTransforms();
  72240. if (scaleChildren) {
  72241. for (var i = 0; i < len; i++) {
  72242. this.children[i].scale(x, y, z, scaleChildren);
  72243. }
  72244. }
  72245. this.markAsDirty();
  72246. };
  72247. /**
  72248. * Set the yaw, pitch, and roll of the bone in local or world space.
  72249. * @param yaw The rotation of the bone on the y axis.
  72250. * @param pitch The rotation of the bone on the x axis.
  72251. * @param roll The rotation of the bone on the z axis.
  72252. * @param space The space that the axes of rotation are in.
  72253. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72254. */
  72255. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  72256. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72257. var rotMat = Bone._tmpMats[0];
  72258. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  72259. var rotMatInv = Bone._tmpMats[1];
  72260. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72261. rotMatInv.multiplyToRef(rotMat, rotMat);
  72262. this._rotateWithMatrix(rotMat, space, mesh);
  72263. };
  72264. /**
  72265. * Rotate the bone on an axis in local or world space.
  72266. * @param axis The axis to rotate the bone on.
  72267. * @param amount The amount to rotate the bone.
  72268. * @param space The space that the axis is in.
  72269. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72270. */
  72271. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  72272. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72273. var rmat = Bone._tmpMats[0];
  72274. rmat.m[12] = 0;
  72275. rmat.m[13] = 0;
  72276. rmat.m[14] = 0;
  72277. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  72278. this._rotateWithMatrix(rmat, space, mesh);
  72279. };
  72280. /**
  72281. * Set the rotation of the bone to a particular axis angle in local or world space.
  72282. * @param axis The axis to rotate the bone on.
  72283. * @param angle The angle that the bone should be rotated to.
  72284. * @param space The space that the axis is in.
  72285. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72286. */
  72287. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  72288. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72289. var rotMat = Bone._tmpMats[0];
  72290. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  72291. var rotMatInv = Bone._tmpMats[1];
  72292. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72293. rotMatInv.multiplyToRef(rotMat, rotMat);
  72294. this._rotateWithMatrix(rotMat, space, mesh);
  72295. };
  72296. /**
  72297. * Set the euler rotation of the bone in local of world space.
  72298. * @param rotation The euler rotation that the bone should be set to.
  72299. * @param space The space that the rotation is in.
  72300. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72301. */
  72302. Bone.prototype.setRotation = function (rotation, space, mesh) {
  72303. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72304. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  72305. };
  72306. /**
  72307. * Set the quaternion rotation of the bone in local of world space.
  72308. * @param quat The quaternion rotation that the bone should be set to.
  72309. * @param space The space that the rotation is in.
  72310. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72311. */
  72312. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  72313. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72314. var rotMatInv = Bone._tmpMats[0];
  72315. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72316. var rotMat = Bone._tmpMats[1];
  72317. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  72318. rotMatInv.multiplyToRef(rotMat, rotMat);
  72319. this._rotateWithMatrix(rotMat, space, mesh);
  72320. };
  72321. /**
  72322. * Set the rotation matrix of the bone in local of world space.
  72323. * @param rotMat The rotation matrix that the bone should be set to.
  72324. * @param space The space that the rotation is in.
  72325. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72326. */
  72327. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  72328. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72329. var rotMatInv = Bone._tmpMats[0];
  72330. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72331. var rotMat2 = Bone._tmpMats[1];
  72332. rotMat2.copyFrom(rotMat);
  72333. rotMatInv.multiplyToRef(rotMat, rotMat2);
  72334. this._rotateWithMatrix(rotMat2, space, mesh);
  72335. };
  72336. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  72337. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72338. var lmat = this.getLocalMatrix();
  72339. var lx = lmat.m[12];
  72340. var ly = lmat.m[13];
  72341. var lz = lmat.m[14];
  72342. var parent = this.getParent();
  72343. var parentScale = Bone._tmpMats[3];
  72344. var parentScaleInv = Bone._tmpMats[4];
  72345. if (parent) {
  72346. if (space == BABYLON.Space.WORLD) {
  72347. if (mesh) {
  72348. parentScale.copyFrom(mesh.getWorldMatrix());
  72349. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  72350. }
  72351. else {
  72352. parentScale.copyFrom(parent.getAbsoluteTransform());
  72353. }
  72354. }
  72355. else {
  72356. parentScale = parent._scaleMatrix;
  72357. }
  72358. parentScaleInv.copyFrom(parentScale);
  72359. parentScaleInv.invert();
  72360. lmat.multiplyToRef(parentScale, lmat);
  72361. lmat.multiplyToRef(rmat, lmat);
  72362. lmat.multiplyToRef(parentScaleInv, lmat);
  72363. }
  72364. else {
  72365. if (space == BABYLON.Space.WORLD && mesh) {
  72366. parentScale.copyFrom(mesh.getWorldMatrix());
  72367. parentScaleInv.copyFrom(parentScale);
  72368. parentScaleInv.invert();
  72369. lmat.multiplyToRef(parentScale, lmat);
  72370. lmat.multiplyToRef(rmat, lmat);
  72371. lmat.multiplyToRef(parentScaleInv, lmat);
  72372. }
  72373. else {
  72374. lmat.multiplyToRef(rmat, lmat);
  72375. }
  72376. }
  72377. lmat.m[12] = lx;
  72378. lmat.m[13] = ly;
  72379. lmat.m[14] = lz;
  72380. this.computeAbsoluteTransforms();
  72381. this.markAsDirty();
  72382. };
  72383. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  72384. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72385. if (space == BABYLON.Space.WORLD) {
  72386. var scaleMatrix = Bone._tmpMats[2];
  72387. scaleMatrix.copyFrom(this._scaleMatrix);
  72388. rotMatInv.copyFrom(this.getAbsoluteTransform());
  72389. if (mesh) {
  72390. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  72391. var meshScale = Bone._tmpMats[3];
  72392. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  72393. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  72394. }
  72395. rotMatInv.invert();
  72396. scaleMatrix.m[0] *= this._scalingDeterminant;
  72397. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  72398. }
  72399. else {
  72400. rotMatInv.copyFrom(this.getLocalMatrix());
  72401. rotMatInv.invert();
  72402. var scaleMatrix = Bone._tmpMats[2];
  72403. scaleMatrix.copyFrom(this._scaleMatrix);
  72404. if (this._parent) {
  72405. var pscaleMatrix = Bone._tmpMats[3];
  72406. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  72407. pscaleMatrix.invert();
  72408. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  72409. }
  72410. else {
  72411. scaleMatrix.m[0] *= this._scalingDeterminant;
  72412. }
  72413. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  72414. }
  72415. };
  72416. /**
  72417. * Get the scale of the bone
  72418. * @returns the scale of the bone
  72419. */
  72420. Bone.prototype.getScale = function () {
  72421. return this._scaleVector.clone();
  72422. };
  72423. /**
  72424. * Copy the scale of the bone to a vector3.
  72425. * @param result The vector3 to copy the scale to
  72426. */
  72427. Bone.prototype.getScaleToRef = function (result) {
  72428. result.copyFrom(this._scaleVector);
  72429. };
  72430. /**
  72431. * Get the position of the bone in local or world space.
  72432. * @param space The space that the returned position is in.
  72433. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72434. * @returns The position of the bone
  72435. */
  72436. Bone.prototype.getPosition = function (space, mesh) {
  72437. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72438. if (mesh === void 0) { mesh = null; }
  72439. var pos = BABYLON.Vector3.Zero();
  72440. this.getPositionToRef(space, mesh, pos);
  72441. return pos;
  72442. };
  72443. /**
  72444. * Copy the position of the bone to a vector3 in local or world space.
  72445. * @param space The space that the returned position is in.
  72446. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72447. * @param result The vector3 to copy the position to.
  72448. */
  72449. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  72450. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72451. if (space == BABYLON.Space.LOCAL) {
  72452. var lm = this.getLocalMatrix();
  72453. result.x = lm.m[12];
  72454. result.y = lm.m[13];
  72455. result.z = lm.m[14];
  72456. }
  72457. else {
  72458. var wm = null;
  72459. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72460. if (mesh) {
  72461. wm = mesh.getWorldMatrix();
  72462. }
  72463. this._skeleton.computeAbsoluteTransforms();
  72464. var tmat = Bone._tmpMats[0];
  72465. if (mesh && wm) {
  72466. tmat.copyFrom(this.getAbsoluteTransform());
  72467. tmat.multiplyToRef(wm, tmat);
  72468. }
  72469. else {
  72470. tmat = this.getAbsoluteTransform();
  72471. }
  72472. result.x = tmat.m[12];
  72473. result.y = tmat.m[13];
  72474. result.z = tmat.m[14];
  72475. }
  72476. };
  72477. /**
  72478. * Get the absolute position of the bone (world space).
  72479. * @param mesh The mesh that this bone is attached to.
  72480. * @returns The absolute position of the bone
  72481. */
  72482. Bone.prototype.getAbsolutePosition = function (mesh) {
  72483. if (mesh === void 0) { mesh = null; }
  72484. var pos = BABYLON.Vector3.Zero();
  72485. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  72486. return pos;
  72487. };
  72488. /**
  72489. * Copy the absolute position of the bone (world space) to the result param.
  72490. * @param mesh The mesh that this bone is attached to.
  72491. * @param result The vector3 to copy the absolute position to.
  72492. */
  72493. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  72494. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  72495. };
  72496. /**
  72497. * Compute the absolute transforms of this bone and its children.
  72498. */
  72499. Bone.prototype.computeAbsoluteTransforms = function () {
  72500. if (this._parent) {
  72501. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  72502. }
  72503. else {
  72504. this._absoluteTransform.copyFrom(this._localMatrix);
  72505. var poseMatrix = this._skeleton.getPoseMatrix();
  72506. if (poseMatrix) {
  72507. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  72508. }
  72509. }
  72510. var children = this.children;
  72511. var len = children.length;
  72512. for (var i = 0; i < len; i++) {
  72513. children[i].computeAbsoluteTransforms();
  72514. }
  72515. };
  72516. Bone.prototype._syncScaleVector = function () {
  72517. var lm = this.getLocalMatrix();
  72518. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  72519. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  72520. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  72521. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  72522. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  72523. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  72524. this._scaleVector.x = xs * Math.sqrt(xsq);
  72525. this._scaleVector.y = ys * Math.sqrt(ysq);
  72526. this._scaleVector.z = zs * Math.sqrt(zsq);
  72527. if (this._parent) {
  72528. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  72529. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  72530. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  72531. }
  72532. BABYLON.Matrix.FromValuesToRef(this._scaleVector.x, 0, 0, 0, 0, this._scaleVector.y, 0, 0, 0, 0, this._scaleVector.z, 0, 0, 0, 0, 1, this._scaleMatrix);
  72533. };
  72534. /**
  72535. * Get the world direction from an axis that is in the local space of the bone.
  72536. * @param localAxis The local direction that is used to compute the world direction.
  72537. * @param mesh The mesh that this bone is attached to.
  72538. * @returns The world direction
  72539. */
  72540. Bone.prototype.getDirection = function (localAxis, mesh) {
  72541. if (mesh === void 0) { mesh = null; }
  72542. var result = BABYLON.Vector3.Zero();
  72543. this.getDirectionToRef(localAxis, mesh, result);
  72544. return result;
  72545. };
  72546. /**
  72547. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  72548. * @param localAxis The local direction that is used to compute the world direction.
  72549. * @param mesh The mesh that this bone is attached to.
  72550. * @param result The vector3 that the world direction will be copied to.
  72551. */
  72552. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  72553. if (mesh === void 0) { mesh = null; }
  72554. var wm = null;
  72555. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72556. if (mesh) {
  72557. wm = mesh.getWorldMatrix();
  72558. }
  72559. this._skeleton.computeAbsoluteTransforms();
  72560. var mat = Bone._tmpMats[0];
  72561. mat.copyFrom(this.getAbsoluteTransform());
  72562. if (mesh && wm) {
  72563. mat.multiplyToRef(wm, mat);
  72564. }
  72565. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  72566. result.normalize();
  72567. };
  72568. /**
  72569. * Get the euler rotation of the bone in local or world space.
  72570. * @param space The space that the rotation should be in.
  72571. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72572. * @returns The euler rotation
  72573. */
  72574. Bone.prototype.getRotation = function (space, mesh) {
  72575. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72576. if (mesh === void 0) { mesh = null; }
  72577. var result = BABYLON.Vector3.Zero();
  72578. this.getRotationToRef(space, mesh, result);
  72579. return result;
  72580. };
  72581. /**
  72582. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  72583. * @param space The space that the rotation should be in.
  72584. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72585. * @param result The vector3 that the rotation should be copied to.
  72586. */
  72587. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  72588. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72589. if (mesh === void 0) { mesh = null; }
  72590. var quat = Bone._tmpQuat;
  72591. this.getRotationQuaternionToRef(space, mesh, quat);
  72592. quat.toEulerAnglesToRef(result);
  72593. };
  72594. /**
  72595. * Get the quaternion rotation of the bone in either local or world space.
  72596. * @param space The space that the rotation should be in.
  72597. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72598. * @returns The quaternion rotation
  72599. */
  72600. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  72601. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72602. if (mesh === void 0) { mesh = null; }
  72603. var result = BABYLON.Quaternion.Identity();
  72604. this.getRotationQuaternionToRef(space, mesh, result);
  72605. return result;
  72606. };
  72607. /**
  72608. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  72609. * @param space The space that the rotation should be in.
  72610. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72611. * @param result The quaternion that the rotation should be copied to.
  72612. */
  72613. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  72614. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72615. if (mesh === void 0) { mesh = null; }
  72616. if (space == BABYLON.Space.LOCAL) {
  72617. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  72618. }
  72619. else {
  72620. var mat = Bone._tmpMats[0];
  72621. var amat = this.getAbsoluteTransform();
  72622. if (mesh) {
  72623. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  72624. }
  72625. else {
  72626. mat.copyFrom(amat);
  72627. }
  72628. mat.m[0] *= this._scalingDeterminant;
  72629. mat.m[1] *= this._scalingDeterminant;
  72630. mat.m[2] *= this._scalingDeterminant;
  72631. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  72632. }
  72633. };
  72634. /**
  72635. * Get the rotation matrix of the bone in local or world space.
  72636. * @param space The space that the rotation should be in.
  72637. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72638. * @returns The rotation matrix
  72639. */
  72640. Bone.prototype.getRotationMatrix = function (space, mesh) {
  72641. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72642. var result = BABYLON.Matrix.Identity();
  72643. this.getRotationMatrixToRef(space, mesh, result);
  72644. return result;
  72645. };
  72646. /**
  72647. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  72648. * @param space The space that the rotation should be in.
  72649. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72650. * @param result The quaternion that the rotation should be copied to.
  72651. */
  72652. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  72653. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72654. if (space == BABYLON.Space.LOCAL) {
  72655. this.getLocalMatrix().getRotationMatrixToRef(result);
  72656. }
  72657. else {
  72658. var mat = Bone._tmpMats[0];
  72659. var amat = this.getAbsoluteTransform();
  72660. if (mesh) {
  72661. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  72662. }
  72663. else {
  72664. mat.copyFrom(amat);
  72665. }
  72666. mat.m[0] *= this._scalingDeterminant;
  72667. mat.m[1] *= this._scalingDeterminant;
  72668. mat.m[2] *= this._scalingDeterminant;
  72669. mat.getRotationMatrixToRef(result);
  72670. }
  72671. };
  72672. /**
  72673. * Get the world position of a point that is in the local space of the bone.
  72674. * @param position The local position
  72675. * @param mesh The mesh that this bone is attached to.
  72676. * @returns The world position
  72677. */
  72678. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  72679. if (mesh === void 0) { mesh = null; }
  72680. var result = BABYLON.Vector3.Zero();
  72681. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  72682. return result;
  72683. };
  72684. /**
  72685. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  72686. * @param position The local position
  72687. * @param mesh The mesh that this bone is attached to.
  72688. * @param result The vector3 that the world position should be copied to.
  72689. */
  72690. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  72691. if (mesh === void 0) { mesh = null; }
  72692. var wm = null;
  72693. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72694. if (mesh) {
  72695. wm = mesh.getWorldMatrix();
  72696. }
  72697. this._skeleton.computeAbsoluteTransforms();
  72698. var tmat = Bone._tmpMats[0];
  72699. if (mesh && wm) {
  72700. tmat.copyFrom(this.getAbsoluteTransform());
  72701. tmat.multiplyToRef(wm, tmat);
  72702. }
  72703. else {
  72704. tmat = this.getAbsoluteTransform();
  72705. }
  72706. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  72707. };
  72708. /**
  72709. * Get the local position of a point that is in world space.
  72710. * @param position The world position
  72711. * @param mesh The mesh that this bone is attached to.
  72712. * @returns The local position
  72713. */
  72714. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  72715. if (mesh === void 0) { mesh = null; }
  72716. var result = BABYLON.Vector3.Zero();
  72717. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  72718. return result;
  72719. };
  72720. /**
  72721. * Get the local position of a point that is in world space and copy it to the result param.
  72722. * @param position The world position
  72723. * @param mesh The mesh that this bone is attached to.
  72724. * @param result The vector3 that the local position should be copied to.
  72725. */
  72726. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  72727. if (mesh === void 0) { mesh = null; }
  72728. var wm = null;
  72729. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72730. if (mesh) {
  72731. wm = mesh.getWorldMatrix();
  72732. }
  72733. this._skeleton.computeAbsoluteTransforms();
  72734. var tmat = Bone._tmpMats[0];
  72735. tmat.copyFrom(this.getAbsoluteTransform());
  72736. if (mesh && wm) {
  72737. tmat.multiplyToRef(wm, tmat);
  72738. }
  72739. tmat.invert();
  72740. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  72741. };
  72742. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72743. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  72744. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  72745. return Bone;
  72746. }(BABYLON.Node));
  72747. BABYLON.Bone = Bone;
  72748. })(BABYLON || (BABYLON = {}));
  72749. //# sourceMappingURL=babylon.bone.js.map
  72750. var BABYLON;
  72751. (function (BABYLON) {
  72752. var BoneIKController = /** @class */ (function () {
  72753. function BoneIKController(mesh, bone, options) {
  72754. this.targetPosition = BABYLON.Vector3.Zero();
  72755. this.poleTargetPosition = BABYLON.Vector3.Zero();
  72756. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  72757. this.poleAngle = 0;
  72758. this.slerpAmount = 1;
  72759. this._bone1Quat = BABYLON.Quaternion.Identity();
  72760. this._bone1Mat = BABYLON.Matrix.Identity();
  72761. this._bone2Ang = Math.PI;
  72762. this._maxAngle = Math.PI;
  72763. this._rightHandedSystem = false;
  72764. this._bendAxis = BABYLON.Vector3.Right();
  72765. this._slerping = false;
  72766. this._adjustRoll = 0;
  72767. this._bone2 = bone;
  72768. this._bone1 = bone.getParent();
  72769. if (!this._bone1) {
  72770. return;
  72771. }
  72772. this.mesh = mesh;
  72773. var bonePos = bone.getPosition();
  72774. if (bone.getAbsoluteTransform().determinant() > 0) {
  72775. this._rightHandedSystem = true;
  72776. this._bendAxis.x = 0;
  72777. this._bendAxis.y = 0;
  72778. this._bendAxis.z = -1;
  72779. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  72780. this._adjustRoll = Math.PI * .5;
  72781. this._bendAxis.z = 1;
  72782. }
  72783. }
  72784. if (this._bone1.length) {
  72785. var boneScale1 = this._bone1.getScale();
  72786. var boneScale2 = this._bone2.getScale();
  72787. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  72788. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  72789. }
  72790. else if (this._bone1.children[0]) {
  72791. mesh.computeWorldMatrix(true);
  72792. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  72793. var pos2 = this._bone2.getAbsolutePosition(mesh);
  72794. var pos3 = this._bone1.getAbsolutePosition(mesh);
  72795. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  72796. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  72797. }
  72798. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  72799. this.maxAngle = Math.PI;
  72800. if (options) {
  72801. if (options.targetMesh) {
  72802. this.targetMesh = options.targetMesh;
  72803. this.targetMesh.computeWorldMatrix(true);
  72804. }
  72805. if (options.poleTargetMesh) {
  72806. this.poleTargetMesh = options.poleTargetMesh;
  72807. this.poleTargetMesh.computeWorldMatrix(true);
  72808. }
  72809. else if (options.poleTargetBone) {
  72810. this.poleTargetBone = options.poleTargetBone;
  72811. }
  72812. else if (this._bone1.getParent()) {
  72813. this.poleTargetBone = this._bone1.getParent();
  72814. }
  72815. if (options.poleTargetLocalOffset) {
  72816. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  72817. }
  72818. if (options.poleAngle) {
  72819. this.poleAngle = options.poleAngle;
  72820. }
  72821. if (options.bendAxis) {
  72822. this._bendAxis.copyFrom(options.bendAxis);
  72823. }
  72824. if (options.maxAngle) {
  72825. this.maxAngle = options.maxAngle;
  72826. }
  72827. if (options.slerpAmount) {
  72828. this.slerpAmount = options.slerpAmount;
  72829. }
  72830. }
  72831. }
  72832. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  72833. get: function () {
  72834. return this._maxAngle;
  72835. },
  72836. set: function (value) {
  72837. this._setMaxAngle(value);
  72838. },
  72839. enumerable: true,
  72840. configurable: true
  72841. });
  72842. BoneIKController.prototype._setMaxAngle = function (ang) {
  72843. if (ang < 0) {
  72844. ang = 0;
  72845. }
  72846. if (ang > Math.PI || ang == undefined) {
  72847. ang = Math.PI;
  72848. }
  72849. this._maxAngle = ang;
  72850. var a = this._bone1Length;
  72851. var b = this._bone2Length;
  72852. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  72853. };
  72854. BoneIKController.prototype.update = function () {
  72855. var bone1 = this._bone1;
  72856. if (!bone1) {
  72857. return;
  72858. }
  72859. var target = this.targetPosition;
  72860. var poleTarget = this.poleTargetPosition;
  72861. var mat1 = BoneIKController._tmpMats[0];
  72862. var mat2 = BoneIKController._tmpMats[1];
  72863. if (this.targetMesh) {
  72864. target.copyFrom(this.targetMesh.getAbsolutePosition());
  72865. }
  72866. if (this.poleTargetBone) {
  72867. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  72868. }
  72869. else if (this.poleTargetMesh) {
  72870. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  72871. }
  72872. var bonePos = BoneIKController._tmpVecs[0];
  72873. var zaxis = BoneIKController._tmpVecs[1];
  72874. var xaxis = BoneIKController._tmpVecs[2];
  72875. var yaxis = BoneIKController._tmpVecs[3];
  72876. var upAxis = BoneIKController._tmpVecs[4];
  72877. var _tmpQuat = BoneIKController._tmpQuat;
  72878. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  72879. poleTarget.subtractToRef(bonePos, upAxis);
  72880. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  72881. upAxis.y = 1;
  72882. }
  72883. else {
  72884. upAxis.normalize();
  72885. }
  72886. target.subtractToRef(bonePos, yaxis);
  72887. yaxis.normalize();
  72888. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  72889. zaxis.normalize();
  72890. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  72891. xaxis.normalize();
  72892. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  72893. var a = this._bone1Length;
  72894. var b = this._bone2Length;
  72895. var c = BABYLON.Vector3.Distance(bonePos, target);
  72896. if (this._maxReach > 0) {
  72897. c = Math.min(this._maxReach, c);
  72898. }
  72899. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  72900. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  72901. if (acosa > 1) {
  72902. acosa = 1;
  72903. }
  72904. if (acosb > 1) {
  72905. acosb = 1;
  72906. }
  72907. if (acosa < -1) {
  72908. acosa = -1;
  72909. }
  72910. if (acosb < -1) {
  72911. acosb = -1;
  72912. }
  72913. var angA = Math.acos(acosa);
  72914. var angB = Math.acos(acosb);
  72915. var angC = -angA - angB;
  72916. if (this._rightHandedSystem) {
  72917. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  72918. mat2.multiplyToRef(mat1, mat1);
  72919. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  72920. mat2.multiplyToRef(mat1, mat1);
  72921. }
  72922. else {
  72923. var _tmpVec = BoneIKController._tmpVecs[5];
  72924. _tmpVec.copyFrom(this._bendAxis);
  72925. _tmpVec.x *= -1;
  72926. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  72927. mat2.multiplyToRef(mat1, mat1);
  72928. }
  72929. if (this.poleAngle) {
  72930. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  72931. mat1.multiplyToRef(mat2, mat1);
  72932. }
  72933. if (this._bone1) {
  72934. if (this.slerpAmount < 1) {
  72935. if (!this._slerping) {
  72936. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  72937. }
  72938. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  72939. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  72940. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  72941. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  72942. this._slerping = true;
  72943. }
  72944. else {
  72945. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  72946. this._bone1Mat.copyFrom(mat1);
  72947. this._slerping = false;
  72948. }
  72949. }
  72950. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  72951. this._bone2Ang = angC;
  72952. };
  72953. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72954. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  72955. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  72956. return BoneIKController;
  72957. }());
  72958. BABYLON.BoneIKController = BoneIKController;
  72959. })(BABYLON || (BABYLON = {}));
  72960. //# sourceMappingURL=babylon.boneIKController.js.map
  72961. var BABYLON;
  72962. (function (BABYLON) {
  72963. var BoneLookController = /** @class */ (function () {
  72964. /**
  72965. * Create a BoneLookController
  72966. * @param mesh the mesh that the bone belongs to
  72967. * @param bone the bone that will be looking to the target
  72968. * @param target the target Vector3 to look at
  72969. * @param settings optional settings:
  72970. * - maxYaw: the maximum angle the bone will yaw to
  72971. * - minYaw: the minimum angle the bone will yaw to
  72972. * - maxPitch: the maximum angle the bone will pitch to
  72973. * - minPitch: the minimum angle the bone will yaw to
  72974. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  72975. * - upAxis: the up axis of the coordinate system
  72976. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  72977. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  72978. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  72979. * - adjustYaw: used to make an adjustment to the yaw of the bone
  72980. * - adjustPitch: used to make an adjustment to the pitch of the bone
  72981. * - adjustRoll: used to make an adjustment to the roll of the bone
  72982. **/
  72983. function BoneLookController(mesh, bone, target, options) {
  72984. /**
  72985. * The up axis of the coordinate system that is used when the bone is rotated.
  72986. */
  72987. this.upAxis = BABYLON.Vector3.Up();
  72988. /**
  72989. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  72990. */
  72991. this.upAxisSpace = BABYLON.Space.LOCAL;
  72992. /**
  72993. * Used to make an adjustment to the yaw of the bone.
  72994. */
  72995. this.adjustYaw = 0;
  72996. /**
  72997. * Used to make an adjustment to the pitch of the bone.
  72998. */
  72999. this.adjustPitch = 0;
  73000. /**
  73001. * Used to make an adjustment to the roll of the bone.
  73002. */
  73003. this.adjustRoll = 0;
  73004. /**
  73005. * 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).
  73006. */
  73007. this.slerpAmount = 1;
  73008. this._boneQuat = BABYLON.Quaternion.Identity();
  73009. this._slerping = false;
  73010. this._firstFrameSkipped = false;
  73011. this._fowardAxis = BABYLON.Vector3.Forward();
  73012. this.mesh = mesh;
  73013. this.bone = bone;
  73014. this.target = target;
  73015. if (options) {
  73016. if (options.adjustYaw) {
  73017. this.adjustYaw = options.adjustYaw;
  73018. }
  73019. if (options.adjustPitch) {
  73020. this.adjustPitch = options.adjustPitch;
  73021. }
  73022. if (options.adjustRoll) {
  73023. this.adjustRoll = options.adjustRoll;
  73024. }
  73025. if (options.maxYaw != null) {
  73026. this.maxYaw = options.maxYaw;
  73027. }
  73028. else {
  73029. this.maxYaw = Math.PI;
  73030. }
  73031. if (options.minYaw != null) {
  73032. this.minYaw = options.minYaw;
  73033. }
  73034. else {
  73035. this.minYaw = -Math.PI;
  73036. }
  73037. if (options.maxPitch != null) {
  73038. this.maxPitch = options.maxPitch;
  73039. }
  73040. else {
  73041. this.maxPitch = Math.PI;
  73042. }
  73043. if (options.minPitch != null) {
  73044. this.minPitch = options.minPitch;
  73045. }
  73046. else {
  73047. this.minPitch = -Math.PI;
  73048. }
  73049. if (options.slerpAmount != null) {
  73050. this.slerpAmount = options.slerpAmount;
  73051. }
  73052. if (options.upAxis != null) {
  73053. this.upAxis = options.upAxis;
  73054. }
  73055. if (options.upAxisSpace != null) {
  73056. this.upAxisSpace = options.upAxisSpace;
  73057. }
  73058. if (options.yawAxis != null || options.pitchAxis != null) {
  73059. var newYawAxis = BABYLON.Axis.Y;
  73060. var newPitchAxis = BABYLON.Axis.X;
  73061. if (options.yawAxis != null) {
  73062. newYawAxis = options.yawAxis.clone();
  73063. newYawAxis.normalize();
  73064. }
  73065. if (options.pitchAxis != null) {
  73066. newPitchAxis = options.pitchAxis.clone();
  73067. newPitchAxis.normalize();
  73068. }
  73069. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  73070. this._transformYawPitch = BABYLON.Matrix.Identity();
  73071. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  73072. this._transformYawPitchInv = this._transformYawPitch.clone();
  73073. this._transformYawPitch.invert();
  73074. }
  73075. }
  73076. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  73077. this.upAxisSpace = BABYLON.Space.LOCAL;
  73078. }
  73079. }
  73080. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  73081. /**
  73082. * Get/set the minimum yaw angle that the bone can look to.
  73083. */
  73084. get: function () {
  73085. return this._minYaw;
  73086. },
  73087. set: function (value) {
  73088. this._minYaw = value;
  73089. this._minYawSin = Math.sin(value);
  73090. this._minYawCos = Math.cos(value);
  73091. if (this._maxYaw != null) {
  73092. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  73093. this._yawRange = this._maxYaw - this._minYaw;
  73094. }
  73095. },
  73096. enumerable: true,
  73097. configurable: true
  73098. });
  73099. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  73100. /**
  73101. * Get/set the maximum yaw angle that the bone can look to.
  73102. */
  73103. get: function () {
  73104. return this._maxYaw;
  73105. },
  73106. set: function (value) {
  73107. this._maxYaw = value;
  73108. this._maxYawSin = Math.sin(value);
  73109. this._maxYawCos = Math.cos(value);
  73110. if (this._minYaw != null) {
  73111. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  73112. this._yawRange = this._maxYaw - this._minYaw;
  73113. }
  73114. },
  73115. enumerable: true,
  73116. configurable: true
  73117. });
  73118. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  73119. /**
  73120. * Get/set the minimum pitch angle that the bone can look to.
  73121. */
  73122. get: function () {
  73123. return this._minPitch;
  73124. },
  73125. set: function (value) {
  73126. this._minPitch = value;
  73127. this._minPitchTan = Math.tan(value);
  73128. },
  73129. enumerable: true,
  73130. configurable: true
  73131. });
  73132. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  73133. /**
  73134. * Get/set the maximum pitch angle that the bone can look to.
  73135. */
  73136. get: function () {
  73137. return this._maxPitch;
  73138. },
  73139. set: function (value) {
  73140. this._maxPitch = value;
  73141. this._maxPitchTan = Math.tan(value);
  73142. },
  73143. enumerable: true,
  73144. configurable: true
  73145. });
  73146. /**
  73147. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  73148. */
  73149. BoneLookController.prototype.update = function () {
  73150. //skip the first frame when slerping so that the mesh rotation is correct
  73151. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  73152. this._firstFrameSkipped = true;
  73153. return;
  73154. }
  73155. var bone = this.bone;
  73156. var bonePos = BoneLookController._tmpVecs[0];
  73157. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  73158. var target = this.target;
  73159. var _tmpMat1 = BoneLookController._tmpMats[0];
  73160. var _tmpMat2 = BoneLookController._tmpMats[1];
  73161. var mesh = this.mesh;
  73162. var parentBone = bone.getParent();
  73163. var upAxis = BoneLookController._tmpVecs[1];
  73164. upAxis.copyFrom(this.upAxis);
  73165. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  73166. if (this._transformYawPitch) {
  73167. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  73168. }
  73169. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  73170. }
  73171. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  73172. mesh.getDirectionToRef(upAxis, upAxis);
  73173. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  73174. upAxis.normalize();
  73175. }
  73176. }
  73177. var checkYaw = false;
  73178. var checkPitch = false;
  73179. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  73180. checkYaw = true;
  73181. }
  73182. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  73183. checkPitch = true;
  73184. }
  73185. if (checkYaw || checkPitch) {
  73186. var spaceMat = BoneLookController._tmpMats[2];
  73187. var spaceMatInv = BoneLookController._tmpMats[3];
  73188. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  73189. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  73190. }
  73191. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  73192. spaceMat.copyFrom(mesh.getWorldMatrix());
  73193. }
  73194. else {
  73195. var forwardAxis = BoneLookController._tmpVecs[2];
  73196. forwardAxis.copyFrom(this._fowardAxis);
  73197. if (this._transformYawPitch) {
  73198. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  73199. }
  73200. if (parentBone) {
  73201. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  73202. }
  73203. else {
  73204. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  73205. }
  73206. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  73207. rightAxis.normalize();
  73208. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  73209. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  73210. }
  73211. spaceMat.invertToRef(spaceMatInv);
  73212. var xzlen = null;
  73213. if (checkPitch) {
  73214. var localTarget = BoneLookController._tmpVecs[3];
  73215. target.subtractToRef(bonePos, localTarget);
  73216. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  73217. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  73218. var pitch = Math.atan2(localTarget.y, xzlen);
  73219. var newPitch = pitch;
  73220. if (pitch > this._maxPitch) {
  73221. localTarget.y = this._maxPitchTan * xzlen;
  73222. newPitch = this._maxPitch;
  73223. }
  73224. else if (pitch < this._minPitch) {
  73225. localTarget.y = this._minPitchTan * xzlen;
  73226. newPitch = this._minPitch;
  73227. }
  73228. if (pitch != newPitch) {
  73229. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  73230. localTarget.addInPlace(bonePos);
  73231. target = localTarget;
  73232. }
  73233. }
  73234. if (checkYaw) {
  73235. var localTarget = BoneLookController._tmpVecs[4];
  73236. target.subtractToRef(bonePos, localTarget);
  73237. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  73238. var yaw = Math.atan2(localTarget.x, localTarget.z);
  73239. var newYaw = yaw;
  73240. if (yaw > this._maxYaw || yaw < this._minYaw) {
  73241. if (xzlen == null) {
  73242. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  73243. }
  73244. if (this._yawRange > Math.PI) {
  73245. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  73246. localTarget.z = this._maxYawCos * xzlen;
  73247. localTarget.x = this._maxYawSin * xzlen;
  73248. newYaw = this._maxYaw;
  73249. }
  73250. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  73251. localTarget.z = this._minYawCos * xzlen;
  73252. localTarget.x = this._minYawSin * xzlen;
  73253. newYaw = this._minYaw;
  73254. }
  73255. }
  73256. else {
  73257. if (yaw > this._maxYaw) {
  73258. localTarget.z = this._maxYawCos * xzlen;
  73259. localTarget.x = this._maxYawSin * xzlen;
  73260. newYaw = this._maxYaw;
  73261. }
  73262. else if (yaw < this._minYaw) {
  73263. localTarget.z = this._minYawCos * xzlen;
  73264. localTarget.x = this._minYawSin * xzlen;
  73265. newYaw = this._minYaw;
  73266. }
  73267. }
  73268. }
  73269. if (this._slerping && this._yawRange > Math.PI) {
  73270. //are we going to be crossing into the min/max region?
  73271. var boneFwd = BoneLookController._tmpVecs[8];
  73272. boneFwd.copyFrom(BABYLON.Axis.Z);
  73273. if (this._transformYawPitch) {
  73274. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  73275. }
  73276. var boneRotMat = BoneLookController._tmpMats[4];
  73277. this._boneQuat.toRotationMatrix(boneRotMat);
  73278. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  73279. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  73280. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  73281. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  73282. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  73283. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  73284. if (angBtwTar > angBtwMidYaw) {
  73285. if (xzlen == null) {
  73286. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  73287. }
  73288. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  73289. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  73290. if (angBtwMin < angBtwMax) {
  73291. newYaw = boneYaw + Math.PI * .75;
  73292. localTarget.z = Math.cos(newYaw) * xzlen;
  73293. localTarget.x = Math.sin(newYaw) * xzlen;
  73294. }
  73295. else {
  73296. newYaw = boneYaw - Math.PI * .75;
  73297. localTarget.z = Math.cos(newYaw) * xzlen;
  73298. localTarget.x = Math.sin(newYaw) * xzlen;
  73299. }
  73300. }
  73301. }
  73302. if (yaw != newYaw) {
  73303. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  73304. localTarget.addInPlace(bonePos);
  73305. target = localTarget;
  73306. }
  73307. }
  73308. }
  73309. var zaxis = BoneLookController._tmpVecs[5];
  73310. var xaxis = BoneLookController._tmpVecs[6];
  73311. var yaxis = BoneLookController._tmpVecs[7];
  73312. var _tmpQuat = BoneLookController._tmpQuat;
  73313. target.subtractToRef(bonePos, zaxis);
  73314. zaxis.normalize();
  73315. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  73316. xaxis.normalize();
  73317. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  73318. yaxis.normalize();
  73319. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  73320. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  73321. return;
  73322. }
  73323. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  73324. return;
  73325. }
  73326. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  73327. return;
  73328. }
  73329. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  73330. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  73331. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  73332. }
  73333. if (this.slerpAmount < 1) {
  73334. if (!this._slerping) {
  73335. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  73336. }
  73337. if (this._transformYawPitch) {
  73338. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  73339. }
  73340. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  73341. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  73342. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  73343. this._slerping = true;
  73344. }
  73345. else {
  73346. if (this._transformYawPitch) {
  73347. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  73348. }
  73349. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  73350. this._slerping = false;
  73351. }
  73352. };
  73353. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  73354. var angDiff = ang2 - ang1;
  73355. angDiff %= Math.PI * 2;
  73356. if (angDiff > Math.PI) {
  73357. angDiff -= Math.PI * 2;
  73358. }
  73359. else if (angDiff < -Math.PI) {
  73360. angDiff += Math.PI * 2;
  73361. }
  73362. return angDiff;
  73363. };
  73364. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  73365. ang1 %= (2 * Math.PI);
  73366. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  73367. ang2 %= (2 * Math.PI);
  73368. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  73369. var ab = 0;
  73370. if (ang1 < ang2) {
  73371. ab = ang2 - ang1;
  73372. }
  73373. else {
  73374. ab = ang1 - ang2;
  73375. }
  73376. if (ab > Math.PI) {
  73377. ab = Math.PI * 2 - ab;
  73378. }
  73379. return ab;
  73380. };
  73381. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  73382. ang %= (2 * Math.PI);
  73383. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  73384. ang1 %= (2 * Math.PI);
  73385. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  73386. ang2 %= (2 * Math.PI);
  73387. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  73388. if (ang1 < ang2) {
  73389. if (ang > ang1 && ang < ang2) {
  73390. return true;
  73391. }
  73392. }
  73393. else {
  73394. if (ang > ang2 && ang < ang1) {
  73395. return true;
  73396. }
  73397. }
  73398. return false;
  73399. };
  73400. 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()];
  73401. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  73402. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  73403. return BoneLookController;
  73404. }());
  73405. BABYLON.BoneLookController = BoneLookController;
  73406. })(BABYLON || (BABYLON = {}));
  73407. //# sourceMappingURL=babylon.boneLookController.js.map
  73408. var BABYLON;
  73409. (function (BABYLON) {
  73410. var Skeleton = /** @class */ (function () {
  73411. function Skeleton(name, id, scene) {
  73412. this.name = name;
  73413. this.id = id;
  73414. this.bones = new Array();
  73415. this.needInitialSkinMatrix = false;
  73416. this._isDirty = true;
  73417. this._meshesWithPoseMatrix = new Array();
  73418. this._identity = BABYLON.Matrix.Identity();
  73419. this._ranges = {};
  73420. this._lastAbsoluteTransformsUpdateId = -1;
  73421. /**
  73422. * Specifies if the skeleton should be serialized.
  73423. */
  73424. this.doNotSerialize = false;
  73425. // Events
  73426. /**
  73427. * An event triggered before computing the skeleton's matrices
  73428. * @type {BABYLON.Observable}
  73429. */
  73430. this.onBeforeComputeObservable = new BABYLON.Observable();
  73431. this.bones = [];
  73432. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  73433. scene.skeletons.push(this);
  73434. //make sure it will recalculate the matrix next time prepare is called.
  73435. this._isDirty = true;
  73436. }
  73437. // Members
  73438. Skeleton.prototype.getTransformMatrices = function (mesh) {
  73439. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  73440. return mesh._bonesTransformMatrices;
  73441. }
  73442. if (!this._transformMatrices) {
  73443. this.prepare();
  73444. }
  73445. return this._transformMatrices;
  73446. };
  73447. Skeleton.prototype.getScene = function () {
  73448. return this._scene;
  73449. };
  73450. // Methods
  73451. /**
  73452. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  73453. */
  73454. Skeleton.prototype.toString = function (fullDetails) {
  73455. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  73456. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  73457. if (fullDetails) {
  73458. ret += ", Ranges: {";
  73459. var first = true;
  73460. for (var name_1 in this._ranges) {
  73461. if (first) {
  73462. ret += ", ";
  73463. first = false;
  73464. }
  73465. ret += name_1;
  73466. }
  73467. ret += "}";
  73468. }
  73469. return ret;
  73470. };
  73471. /**
  73472. * Get bone's index searching by name
  73473. * @param {string} name is bone's name to search for
  73474. * @return {number} Indice of the bone. Returns -1 if not found
  73475. */
  73476. Skeleton.prototype.getBoneIndexByName = function (name) {
  73477. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  73478. if (this.bones[boneIndex].name === name) {
  73479. return boneIndex;
  73480. }
  73481. }
  73482. return -1;
  73483. };
  73484. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  73485. // check name not already in use
  73486. if (!this._ranges[name]) {
  73487. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  73488. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  73489. if (this.bones[i].animations[0]) {
  73490. this.bones[i].animations[0].createRange(name, from, to);
  73491. }
  73492. }
  73493. }
  73494. };
  73495. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  73496. if (deleteFrames === void 0) { deleteFrames = true; }
  73497. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  73498. if (this.bones[i].animations[0]) {
  73499. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  73500. }
  73501. }
  73502. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  73503. };
  73504. Skeleton.prototype.getAnimationRange = function (name) {
  73505. return this._ranges[name];
  73506. };
  73507. /**
  73508. * Returns as an Array, all AnimationRanges defined on this skeleton
  73509. */
  73510. Skeleton.prototype.getAnimationRanges = function () {
  73511. var animationRanges = [];
  73512. var name;
  73513. var i = 0;
  73514. for (name in this._ranges) {
  73515. animationRanges[i] = this._ranges[name];
  73516. i++;
  73517. }
  73518. return animationRanges;
  73519. };
  73520. /**
  73521. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  73522. */
  73523. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  73524. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  73525. if (this._ranges[name] || !source.getAnimationRange(name)) {
  73526. return false;
  73527. }
  73528. var ret = true;
  73529. var frameOffset = this._getHighestAnimationFrame() + 1;
  73530. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  73531. var boneDict = {};
  73532. var sourceBones = source.bones;
  73533. var nBones;
  73534. var i;
  73535. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  73536. boneDict[sourceBones[i].name] = sourceBones[i];
  73537. }
  73538. if (this.bones.length !== sourceBones.length) {
  73539. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  73540. ret = false;
  73541. }
  73542. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  73543. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  73544. var boneName = this.bones[i].name;
  73545. var sourceBone = boneDict[boneName];
  73546. if (sourceBone) {
  73547. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  73548. }
  73549. else {
  73550. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  73551. ret = false;
  73552. }
  73553. }
  73554. // do not call createAnimationRange(), since it also is done to bones, which was already done
  73555. var range = source.getAnimationRange(name);
  73556. if (range) {
  73557. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  73558. }
  73559. return ret;
  73560. };
  73561. Skeleton.prototype.returnToRest = function () {
  73562. for (var index = 0; index < this.bones.length; index++) {
  73563. this.bones[index].returnToRest();
  73564. }
  73565. };
  73566. Skeleton.prototype._getHighestAnimationFrame = function () {
  73567. var ret = 0;
  73568. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  73569. if (this.bones[i].animations[0]) {
  73570. var highest = this.bones[i].animations[0].getHighestFrame();
  73571. if (ret < highest) {
  73572. ret = highest;
  73573. }
  73574. }
  73575. }
  73576. return ret;
  73577. };
  73578. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  73579. var range = this.getAnimationRange(name);
  73580. if (!range) {
  73581. return null;
  73582. }
  73583. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  73584. };
  73585. Skeleton.prototype._markAsDirty = function () {
  73586. this._isDirty = true;
  73587. };
  73588. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  73589. this._meshesWithPoseMatrix.push(mesh);
  73590. };
  73591. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  73592. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  73593. if (index > -1) {
  73594. this._meshesWithPoseMatrix.splice(index, 1);
  73595. }
  73596. };
  73597. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  73598. this.onBeforeComputeObservable.notifyObservers(this);
  73599. for (var index = 0; index < this.bones.length; index++) {
  73600. var bone = this.bones[index];
  73601. var parentBone = bone.getParent();
  73602. if (parentBone) {
  73603. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  73604. }
  73605. else {
  73606. if (initialSkinMatrix) {
  73607. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  73608. }
  73609. else {
  73610. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  73611. }
  73612. }
  73613. if (bone._index !== -1) {
  73614. var mappedIndex = bone._index === null ? index : bone._index;
  73615. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  73616. }
  73617. }
  73618. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  73619. };
  73620. Skeleton.prototype.prepare = function () {
  73621. if (!this._isDirty) {
  73622. return;
  73623. }
  73624. if (this.needInitialSkinMatrix) {
  73625. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  73626. var mesh = this._meshesWithPoseMatrix[index];
  73627. var poseMatrix = mesh.getPoseMatrix();
  73628. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  73629. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  73630. }
  73631. if (this._synchronizedWithMesh !== mesh) {
  73632. this._synchronizedWithMesh = mesh;
  73633. // Prepare bones
  73634. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  73635. var bone = this.bones[boneIndex];
  73636. if (!bone.getParent()) {
  73637. var matrix = bone.getBaseMatrix();
  73638. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  73639. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  73640. }
  73641. }
  73642. }
  73643. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  73644. }
  73645. }
  73646. else {
  73647. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  73648. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  73649. }
  73650. this._computeTransformMatrices(this._transformMatrices, null);
  73651. }
  73652. this._isDirty = false;
  73653. this._scene._activeBones.addCount(this.bones.length, false);
  73654. };
  73655. Skeleton.prototype.getAnimatables = function () {
  73656. if (!this._animatables || this._animatables.length !== this.bones.length) {
  73657. this._animatables = [];
  73658. for (var index = 0; index < this.bones.length; index++) {
  73659. this._animatables.push(this.bones[index]);
  73660. }
  73661. }
  73662. return this._animatables;
  73663. };
  73664. Skeleton.prototype.clone = function (name, id) {
  73665. var result = new Skeleton(name, id || name, this._scene);
  73666. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  73667. for (var index = 0; index < this.bones.length; index++) {
  73668. var source = this.bones[index];
  73669. var parentBone = null;
  73670. var parent_1 = source.getParent();
  73671. if (parent_1) {
  73672. var parentIndex = this.bones.indexOf(parent_1);
  73673. parentBone = result.bones[parentIndex];
  73674. }
  73675. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  73676. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  73677. }
  73678. if (this._ranges) {
  73679. result._ranges = {};
  73680. for (var rangeName in this._ranges) {
  73681. var range = this._ranges[rangeName];
  73682. if (range) {
  73683. result._ranges[rangeName] = range.clone();
  73684. }
  73685. }
  73686. }
  73687. this._isDirty = true;
  73688. return result;
  73689. };
  73690. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  73691. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  73692. this.bones.forEach(function (bone) {
  73693. bone.animations.forEach(function (animation) {
  73694. animation.enableBlending = true;
  73695. animation.blendingSpeed = blendingSpeed;
  73696. });
  73697. });
  73698. };
  73699. Skeleton.prototype.dispose = function () {
  73700. this._meshesWithPoseMatrix = [];
  73701. // Animations
  73702. this.getScene().stopAnimation(this);
  73703. // Remove from scene
  73704. this.getScene().removeSkeleton(this);
  73705. };
  73706. Skeleton.prototype.serialize = function () {
  73707. var serializationObject = {};
  73708. serializationObject.name = this.name;
  73709. serializationObject.id = this.id;
  73710. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  73711. serializationObject.bones = [];
  73712. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  73713. for (var index = 0; index < this.bones.length; index++) {
  73714. var bone = this.bones[index];
  73715. var parent_2 = bone.getParent();
  73716. var serializedBone = {
  73717. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  73718. name: bone.name,
  73719. matrix: bone.getBaseMatrix().toArray(),
  73720. rest: bone.getRestPose().toArray()
  73721. };
  73722. serializationObject.bones.push(serializedBone);
  73723. if (bone.length) {
  73724. serializedBone.length = bone.length;
  73725. }
  73726. if (bone.animations && bone.animations.length > 0) {
  73727. serializedBone.animation = bone.animations[0].serialize();
  73728. }
  73729. serializationObject.ranges = [];
  73730. for (var name in this._ranges) {
  73731. var source = this._ranges[name];
  73732. if (!source) {
  73733. continue;
  73734. }
  73735. var range = {};
  73736. range.name = name;
  73737. range.from = source.from;
  73738. range.to = source.to;
  73739. serializationObject.ranges.push(range);
  73740. }
  73741. }
  73742. return serializationObject;
  73743. };
  73744. Skeleton.Parse = function (parsedSkeleton, scene) {
  73745. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  73746. if (parsedSkeleton.dimensionsAtRest) {
  73747. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  73748. }
  73749. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  73750. var index;
  73751. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  73752. var parsedBone = parsedSkeleton.bones[index];
  73753. var parentBone = null;
  73754. if (parsedBone.parentBoneIndex > -1) {
  73755. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  73756. }
  73757. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  73758. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  73759. if (parsedBone.length) {
  73760. bone.length = parsedBone.length;
  73761. }
  73762. if (parsedBone.animation) {
  73763. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  73764. }
  73765. }
  73766. // placed after bones, so createAnimationRange can cascade down
  73767. if (parsedSkeleton.ranges) {
  73768. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  73769. var data = parsedSkeleton.ranges[index];
  73770. skeleton.createAnimationRange(data.name, data.from, data.to);
  73771. }
  73772. }
  73773. return skeleton;
  73774. };
  73775. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  73776. if (forceUpdate === void 0) { forceUpdate = false; }
  73777. var renderId = this._scene.getRenderId();
  73778. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  73779. this.bones[0].computeAbsoluteTransforms();
  73780. this._lastAbsoluteTransformsUpdateId = renderId;
  73781. }
  73782. };
  73783. Skeleton.prototype.getPoseMatrix = function () {
  73784. var poseMatrix = null;
  73785. if (this._meshesWithPoseMatrix.length > 0) {
  73786. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  73787. }
  73788. return poseMatrix;
  73789. };
  73790. Skeleton.prototype.sortBones = function () {
  73791. var bones = new Array();
  73792. var visited = new Array(this.bones.length);
  73793. for (var index = 0; index < this.bones.length; index++) {
  73794. this._sortBones(index, bones, visited);
  73795. }
  73796. this.bones = bones;
  73797. };
  73798. Skeleton.prototype._sortBones = function (index, bones, visited) {
  73799. if (visited[index]) {
  73800. return;
  73801. }
  73802. visited[index] = true;
  73803. var bone = this.bones[index];
  73804. if (bone._index === undefined) {
  73805. bone._index = index;
  73806. }
  73807. var parentBone = bone.getParent();
  73808. if (parentBone) {
  73809. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  73810. }
  73811. bones.push(bone);
  73812. };
  73813. return Skeleton;
  73814. }());
  73815. BABYLON.Skeleton = Skeleton;
  73816. })(BABYLON || (BABYLON = {}));
  73817. //# sourceMappingURL=babylon.skeleton.js.map
  73818. var BABYLON;
  73819. (function (BABYLON) {
  73820. var SphericalPolynomial = /** @class */ (function () {
  73821. function SphericalPolynomial() {
  73822. this.x = BABYLON.Vector3.Zero();
  73823. this.y = BABYLON.Vector3.Zero();
  73824. this.z = BABYLON.Vector3.Zero();
  73825. this.xx = BABYLON.Vector3.Zero();
  73826. this.yy = BABYLON.Vector3.Zero();
  73827. this.zz = BABYLON.Vector3.Zero();
  73828. this.xy = BABYLON.Vector3.Zero();
  73829. this.yz = BABYLON.Vector3.Zero();
  73830. this.zx = BABYLON.Vector3.Zero();
  73831. }
  73832. SphericalPolynomial.prototype.addAmbient = function (color) {
  73833. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  73834. this.xx = this.xx.add(colorVector);
  73835. this.yy = this.yy.add(colorVector);
  73836. this.zz = this.zz.add(colorVector);
  73837. };
  73838. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  73839. var result = new SphericalPolynomial();
  73840. result.x = harmonics.L11.scale(1.02333);
  73841. result.y = harmonics.L1_1.scale(1.02333);
  73842. result.z = harmonics.L10.scale(1.02333);
  73843. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  73844. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  73845. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  73846. result.yz = harmonics.L2_1.scale(0.858086);
  73847. result.zx = harmonics.L21.scale(0.858086);
  73848. result.xy = harmonics.L2_2.scale(0.858086);
  73849. result.scale(1.0 / Math.PI);
  73850. return result;
  73851. };
  73852. SphericalPolynomial.prototype.scale = function (scale) {
  73853. this.x = this.x.scale(scale);
  73854. this.y = this.y.scale(scale);
  73855. this.z = this.z.scale(scale);
  73856. this.xx = this.xx.scale(scale);
  73857. this.yy = this.yy.scale(scale);
  73858. this.zz = this.zz.scale(scale);
  73859. this.yz = this.yz.scale(scale);
  73860. this.zx = this.zx.scale(scale);
  73861. this.xy = this.xy.scale(scale);
  73862. };
  73863. return SphericalPolynomial;
  73864. }());
  73865. BABYLON.SphericalPolynomial = SphericalPolynomial;
  73866. var SphericalHarmonics = /** @class */ (function () {
  73867. function SphericalHarmonics() {
  73868. this.L00 = BABYLON.Vector3.Zero();
  73869. this.L1_1 = BABYLON.Vector3.Zero();
  73870. this.L10 = BABYLON.Vector3.Zero();
  73871. this.L11 = BABYLON.Vector3.Zero();
  73872. this.L2_2 = BABYLON.Vector3.Zero();
  73873. this.L2_1 = BABYLON.Vector3.Zero();
  73874. this.L20 = BABYLON.Vector3.Zero();
  73875. this.L21 = BABYLON.Vector3.Zero();
  73876. this.L22 = BABYLON.Vector3.Zero();
  73877. }
  73878. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  73879. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  73880. var c = colorVector.scale(deltaSolidAngle);
  73881. this.L00 = this.L00.add(c.scale(0.282095));
  73882. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  73883. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  73884. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  73885. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  73886. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  73887. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  73888. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  73889. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  73890. };
  73891. SphericalHarmonics.prototype.scale = function (scale) {
  73892. this.L00 = this.L00.scale(scale);
  73893. this.L1_1 = this.L1_1.scale(scale);
  73894. this.L10 = this.L10.scale(scale);
  73895. this.L11 = this.L11.scale(scale);
  73896. this.L2_2 = this.L2_2.scale(scale);
  73897. this.L2_1 = this.L2_1.scale(scale);
  73898. this.L20 = this.L20.scale(scale);
  73899. this.L21 = this.L21.scale(scale);
  73900. this.L22 = this.L22.scale(scale);
  73901. };
  73902. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  73903. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  73904. //
  73905. // E_lm = A_l * L_lm
  73906. //
  73907. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  73908. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  73909. // the scaling factors are given in equation 9.
  73910. // Constant (Band 0)
  73911. this.L00 = this.L00.scale(3.141593);
  73912. // Linear (Band 1)
  73913. this.L1_1 = this.L1_1.scale(2.094395);
  73914. this.L10 = this.L10.scale(2.094395);
  73915. this.L11 = this.L11.scale(2.094395);
  73916. // Quadratic (Band 2)
  73917. this.L2_2 = this.L2_2.scale(0.785398);
  73918. this.L2_1 = this.L2_1.scale(0.785398);
  73919. this.L20 = this.L20.scale(0.785398);
  73920. this.L21 = this.L21.scale(0.785398);
  73921. this.L22 = this.L22.scale(0.785398);
  73922. };
  73923. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  73924. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  73925. // L = (1/pi) * E * rho
  73926. //
  73927. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  73928. this.scale(1.0 / Math.PI);
  73929. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  73930. // (The pixel shader must apply albedo after texture fetches, etc).
  73931. };
  73932. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  73933. var result = new SphericalHarmonics();
  73934. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  73935. result.L1_1 = polynomial.y.scale(0.977204);
  73936. result.L10 = polynomial.z.scale(0.977204);
  73937. result.L11 = polynomial.x.scale(0.977204);
  73938. result.L2_2 = polynomial.xy.scale(1.16538);
  73939. result.L2_1 = polynomial.yz.scale(1.16538);
  73940. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  73941. result.L21 = polynomial.zx.scale(1.16538);
  73942. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  73943. result.scale(Math.PI);
  73944. return result;
  73945. };
  73946. return SphericalHarmonics;
  73947. }());
  73948. BABYLON.SphericalHarmonics = SphericalHarmonics;
  73949. })(BABYLON || (BABYLON = {}));
  73950. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  73951. var BABYLON;
  73952. (function (BABYLON) {
  73953. var FileFaceOrientation = /** @class */ (function () {
  73954. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  73955. this.name = name;
  73956. this.worldAxisForNormal = worldAxisForNormal;
  73957. this.worldAxisForFileX = worldAxisForFileX;
  73958. this.worldAxisForFileY = worldAxisForFileY;
  73959. }
  73960. return FileFaceOrientation;
  73961. }());
  73962. ;
  73963. /**
  73964. * Helper class dealing with the extraction of spherical polynomial dataArray
  73965. * from a cube map.
  73966. */
  73967. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  73968. function CubeMapToSphericalPolynomialTools() {
  73969. }
  73970. /**
  73971. * Converts a texture to the according Spherical Polynomial data.
  73972. * This extracts the first 3 orders only as they are the only one used in the lighting.
  73973. *
  73974. * @param texture The texture to extract the information from.
  73975. * @return The Spherical Polynomial data.
  73976. */
  73977. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  73978. if (!texture.isCube) {
  73979. // Only supports cube Textures currently.
  73980. return null;
  73981. }
  73982. var size = texture.getSize().width;
  73983. var right = texture.readPixels(0);
  73984. var left = texture.readPixels(1);
  73985. var up;
  73986. var down;
  73987. if (texture.isRenderTarget) {
  73988. up = texture.readPixels(3);
  73989. down = texture.readPixels(2);
  73990. }
  73991. else {
  73992. up = texture.readPixels(2);
  73993. down = texture.readPixels(3);
  73994. }
  73995. var front = texture.readPixels(4);
  73996. var back = texture.readPixels(5);
  73997. var gammaSpace = texture.gammaSpace;
  73998. // Always read as RGBA.
  73999. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  74000. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74001. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74002. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74003. }
  74004. var cubeInfo = {
  74005. size: size,
  74006. right: right,
  74007. left: left,
  74008. up: up,
  74009. down: down,
  74010. front: front,
  74011. back: back,
  74012. format: format,
  74013. type: type,
  74014. gammaSpace: gammaSpace,
  74015. };
  74016. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  74017. };
  74018. /**
  74019. * Converts a cubemap to the according Spherical Polynomial data.
  74020. * This extracts the first 3 orders only as they are the only one used in the lighting.
  74021. *
  74022. * @param cubeInfo The Cube map to extract the information from.
  74023. * @return The Spherical Polynomial data.
  74024. */
  74025. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  74026. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  74027. var totalSolidAngle = 0.0;
  74028. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  74029. var du = 2.0 / cubeInfo.size;
  74030. var dv = du;
  74031. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  74032. var minUV = du * 0.5 - 1.0;
  74033. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74034. var fileFace = this.FileFaces[faceIndex];
  74035. var dataArray = cubeInfo[fileFace.name];
  74036. var v = minUV;
  74037. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  74038. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  74039. // Because SP is still linear, so summation is fine in that basis.
  74040. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  74041. for (var y = 0; y < cubeInfo.size; y++) {
  74042. var u = minUV;
  74043. for (var x = 0; x < cubeInfo.size; x++) {
  74044. // World direction (not normalised)
  74045. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  74046. worldDirection.normalize();
  74047. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  74048. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  74049. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  74050. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  74051. // Handle Integer types.
  74052. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74053. r /= 255;
  74054. g /= 255;
  74055. b /= 255;
  74056. }
  74057. // Handle Gamma space textures.
  74058. if (cubeInfo.gammaSpace) {
  74059. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  74060. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  74061. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  74062. }
  74063. var color = new BABYLON.Color3(r, g, b);
  74064. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  74065. totalSolidAngle += deltaSolidAngle;
  74066. u += du;
  74067. }
  74068. v += dv;
  74069. }
  74070. }
  74071. // Solid angle for entire sphere is 4*pi
  74072. var sphereSolidAngle = 4.0 * Math.PI;
  74073. // Adjust the solid angle to allow for how many faces we processed.
  74074. var facesProcessed = 6.0;
  74075. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  74076. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  74077. // This is needed because the numerical integration over the cube uses a
  74078. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  74079. // and also to compensate for accumulative error due to float precision in the summation.
  74080. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  74081. sphericalHarmonics.scale(correctionFactor);
  74082. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  74083. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  74084. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  74085. };
  74086. CubeMapToSphericalPolynomialTools.FileFaces = [
  74087. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  74088. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  74089. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  74090. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  74091. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  74092. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  74093. ];
  74094. return CubeMapToSphericalPolynomialTools;
  74095. }());
  74096. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  74097. })(BABYLON || (BABYLON = {}));
  74098. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  74099. var BABYLON;
  74100. (function (BABYLON) {
  74101. /**
  74102. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  74103. */
  74104. var PanoramaToCubeMapTools = /** @class */ (function () {
  74105. function PanoramaToCubeMapTools() {
  74106. }
  74107. /**
  74108. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  74109. *
  74110. * @param float32Array The source data.
  74111. * @param inputWidth The width of the input panorama.
  74112. * @param inputhHeight The height of the input panorama.
  74113. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  74114. * @return The cubemap data
  74115. */
  74116. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  74117. if (!float32Array) {
  74118. throw "ConvertPanoramaToCubemap: input cannot be null";
  74119. }
  74120. if (float32Array.length != inputWidth * inputHeight * 3) {
  74121. throw "ConvertPanoramaToCubemap: input size is wrong";
  74122. }
  74123. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  74124. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  74125. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  74126. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  74127. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  74128. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  74129. return {
  74130. front: textureFront,
  74131. back: textureBack,
  74132. left: textureLeft,
  74133. right: textureRight,
  74134. up: textureUp,
  74135. down: textureDown,
  74136. size: size,
  74137. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  74138. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  74139. gammaSpace: false,
  74140. };
  74141. };
  74142. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  74143. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  74144. var textureArray = new Float32Array(buffer);
  74145. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  74146. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  74147. var dy = 1 / texSize;
  74148. var fy = 0;
  74149. for (var y = 0; y < texSize; y++) {
  74150. var xv1 = faceData[0];
  74151. var xv2 = faceData[2];
  74152. for (var x = 0; x < texSize; x++) {
  74153. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  74154. v.normalize();
  74155. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  74156. // 3 channels per pixels
  74157. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  74158. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  74159. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  74160. xv1 = xv1.add(rotDX1);
  74161. xv2 = xv2.add(rotDX2);
  74162. }
  74163. fy += dy;
  74164. }
  74165. return textureArray;
  74166. };
  74167. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  74168. var theta = Math.atan2(vDir.z, vDir.x);
  74169. var phi = Math.acos(vDir.y);
  74170. while (theta < -Math.PI)
  74171. theta += 2 * Math.PI;
  74172. while (theta > Math.PI)
  74173. theta -= 2 * Math.PI;
  74174. var dx = theta / Math.PI;
  74175. var dy = phi / Math.PI;
  74176. // recenter.
  74177. dx = dx * 0.5 + 0.5;
  74178. var px = Math.round(dx * inputWidth);
  74179. if (px < 0)
  74180. px = 0;
  74181. else if (px >= inputWidth)
  74182. px = inputWidth - 1;
  74183. var py = Math.round(dy * inputHeight);
  74184. if (py < 0)
  74185. py = 0;
  74186. else if (py >= inputHeight)
  74187. py = inputHeight - 1;
  74188. var inputY = (inputHeight - py - 1);
  74189. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  74190. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  74191. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  74192. return {
  74193. r: r,
  74194. g: g,
  74195. b: b
  74196. };
  74197. };
  74198. PanoramaToCubeMapTools.FACE_FRONT = [
  74199. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  74200. new BABYLON.Vector3(1.0, -1.0, -1.0),
  74201. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  74202. new BABYLON.Vector3(1.0, 1.0, -1.0)
  74203. ];
  74204. PanoramaToCubeMapTools.FACE_BACK = [
  74205. new BABYLON.Vector3(1.0, -1.0, 1.0),
  74206. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  74207. new BABYLON.Vector3(1.0, 1.0, 1.0),
  74208. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  74209. ];
  74210. PanoramaToCubeMapTools.FACE_RIGHT = [
  74211. new BABYLON.Vector3(1.0, -1.0, -1.0),
  74212. new BABYLON.Vector3(1.0, -1.0, 1.0),
  74213. new BABYLON.Vector3(1.0, 1.0, -1.0),
  74214. new BABYLON.Vector3(1.0, 1.0, 1.0)
  74215. ];
  74216. PanoramaToCubeMapTools.FACE_LEFT = [
  74217. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  74218. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  74219. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  74220. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  74221. ];
  74222. PanoramaToCubeMapTools.FACE_DOWN = [
  74223. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  74224. new BABYLON.Vector3(1.0, 1.0, -1.0),
  74225. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  74226. new BABYLON.Vector3(1.0, 1.0, 1.0)
  74227. ];
  74228. PanoramaToCubeMapTools.FACE_UP = [
  74229. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  74230. new BABYLON.Vector3(1.0, -1.0, 1.0),
  74231. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  74232. new BABYLON.Vector3(1.0, -1.0, -1.0)
  74233. ];
  74234. return PanoramaToCubeMapTools;
  74235. }());
  74236. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  74237. })(BABYLON || (BABYLON = {}));
  74238. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  74239. var BABYLON;
  74240. (function (BABYLON) {
  74241. ;
  74242. /**
  74243. * This groups tools to convert HDR texture to native colors array.
  74244. */
  74245. var HDRTools = /** @class */ (function () {
  74246. function HDRTools() {
  74247. }
  74248. HDRTools.Ldexp = function (mantissa, exponent) {
  74249. if (exponent > 1023) {
  74250. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  74251. }
  74252. if (exponent < -1074) {
  74253. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  74254. }
  74255. return mantissa * Math.pow(2, exponent);
  74256. };
  74257. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  74258. if (exponent > 0) {
  74259. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  74260. float32array[index + 0] = red * exponent;
  74261. float32array[index + 1] = green * exponent;
  74262. float32array[index + 2] = blue * exponent;
  74263. }
  74264. else {
  74265. float32array[index + 0] = 0;
  74266. float32array[index + 1] = 0;
  74267. float32array[index + 2] = 0;
  74268. }
  74269. };
  74270. HDRTools.readStringLine = function (uint8array, startIndex) {
  74271. var line = "";
  74272. var character = "";
  74273. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  74274. character = String.fromCharCode(uint8array[i]);
  74275. if (character == "\n") {
  74276. break;
  74277. }
  74278. line += character;
  74279. }
  74280. return line;
  74281. };
  74282. /**
  74283. * Reads header information from an RGBE texture stored in a native array.
  74284. * More information on this format are available here:
  74285. * https://en.wikipedia.org/wiki/RGBE_image_format
  74286. *
  74287. * @param uint8array The binary file stored in native array.
  74288. * @return The header information.
  74289. */
  74290. HDRTools.RGBE_ReadHeader = function (uint8array) {
  74291. var height = 0;
  74292. var width = 0;
  74293. var line = this.readStringLine(uint8array, 0);
  74294. if (line[0] != '#' || line[1] != '?') {
  74295. throw "Bad HDR Format.";
  74296. }
  74297. var endOfHeader = false;
  74298. var findFormat = false;
  74299. var lineIndex = 0;
  74300. do {
  74301. lineIndex += (line.length + 1);
  74302. line = this.readStringLine(uint8array, lineIndex);
  74303. if (line == "FORMAT=32-bit_rle_rgbe") {
  74304. findFormat = true;
  74305. }
  74306. else if (line.length == 0) {
  74307. endOfHeader = true;
  74308. }
  74309. } while (!endOfHeader);
  74310. if (!findFormat) {
  74311. throw "HDR Bad header format, unsupported FORMAT";
  74312. }
  74313. lineIndex += (line.length + 1);
  74314. line = this.readStringLine(uint8array, lineIndex);
  74315. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  74316. var match = sizeRegexp.exec(line);
  74317. // TODO. Support +Y and -X if needed.
  74318. if (!match || match.length < 3) {
  74319. throw "HDR Bad header format, no size";
  74320. }
  74321. width = parseInt(match[2]);
  74322. height = parseInt(match[1]);
  74323. if (width < 8 || width > 0x7fff) {
  74324. throw "HDR Bad header format, unsupported size";
  74325. }
  74326. lineIndex += (line.length + 1);
  74327. return {
  74328. height: height,
  74329. width: width,
  74330. dataPosition: lineIndex
  74331. };
  74332. };
  74333. /**
  74334. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  74335. * This RGBE texture needs to store the information as a panorama.
  74336. *
  74337. * More information on this format are available here:
  74338. * https://en.wikipedia.org/wiki/RGBE_image_format
  74339. *
  74340. * @param buffer The binary file stored in an array buffer.
  74341. * @param size The expected size of the extracted cubemap.
  74342. * @return The Cube Map information.
  74343. */
  74344. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  74345. var uint8array = new Uint8Array(buffer);
  74346. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  74347. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  74348. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  74349. return cubeMapData;
  74350. };
  74351. /**
  74352. * Returns the pixels data extracted from an RGBE texture.
  74353. * This pixels will be stored left to right up to down in the R G B order in one array.
  74354. *
  74355. * More information on this format are available here:
  74356. * https://en.wikipedia.org/wiki/RGBE_image_format
  74357. *
  74358. * @param uint8array The binary file stored in an array buffer.
  74359. * @param hdrInfo The header information of the file.
  74360. * @return The pixels data in RGB right to left up to down order.
  74361. */
  74362. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  74363. // Keep for multi format supports.
  74364. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  74365. };
  74366. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  74367. var num_scanlines = hdrInfo.height;
  74368. var scanline_width = hdrInfo.width;
  74369. var a, b, c, d, count;
  74370. var dataIndex = hdrInfo.dataPosition;
  74371. var index = 0, endIndex = 0, i = 0;
  74372. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  74373. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  74374. // 3 channels of 4 bytes per pixel in float.
  74375. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  74376. var resultArray = new Float32Array(resultBuffer);
  74377. // read in each successive scanline
  74378. while (num_scanlines > 0) {
  74379. a = uint8array[dataIndex++];
  74380. b = uint8array[dataIndex++];
  74381. c = uint8array[dataIndex++];
  74382. d = uint8array[dataIndex++];
  74383. if (a != 2 || b != 2 || (c & 0x80)) {
  74384. // this file is not run length encoded
  74385. throw "HDR Bad header format, not RLE";
  74386. }
  74387. if (((c << 8) | d) != scanline_width) {
  74388. throw "HDR Bad header format, wrong scan line width";
  74389. }
  74390. index = 0;
  74391. // read each of the four channels for the scanline into the buffer
  74392. for (i = 0; i < 4; i++) {
  74393. endIndex = (i + 1) * scanline_width;
  74394. while (index < endIndex) {
  74395. a = uint8array[dataIndex++];
  74396. b = uint8array[dataIndex++];
  74397. if (a > 128) {
  74398. // a run of the same value
  74399. count = a - 128;
  74400. if ((count == 0) || (count > endIndex - index)) {
  74401. throw "HDR Bad Format, bad scanline data (run)";
  74402. }
  74403. while (count-- > 0) {
  74404. scanLineArray[index++] = b;
  74405. }
  74406. }
  74407. else {
  74408. // a non-run
  74409. count = a;
  74410. if ((count == 0) || (count > endIndex - index)) {
  74411. throw "HDR Bad Format, bad scanline data (non-run)";
  74412. }
  74413. scanLineArray[index++] = b;
  74414. if (--count > 0) {
  74415. for (var j = 0; j < count; j++) {
  74416. scanLineArray[index++] = uint8array[dataIndex++];
  74417. }
  74418. }
  74419. }
  74420. }
  74421. }
  74422. // now convert data from buffer into floats
  74423. for (i = 0; i < scanline_width; i++) {
  74424. a = scanLineArray[i];
  74425. b = scanLineArray[i + scanline_width];
  74426. c = scanLineArray[i + 2 * scanline_width];
  74427. d = scanLineArray[i + 3 * scanline_width];
  74428. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  74429. }
  74430. num_scanlines--;
  74431. }
  74432. return resultArray;
  74433. };
  74434. return HDRTools;
  74435. }());
  74436. BABYLON.HDRTools = HDRTools;
  74437. })(BABYLON || (BABYLON = {}));
  74438. //# sourceMappingURL=babylon.hdr.js.map
  74439. var BABYLON;
  74440. (function (BABYLON) {
  74441. /**
  74442. * This represents a texture coming from an HDR input.
  74443. *
  74444. * The only supported format is currently panorama picture stored in RGBE format.
  74445. * Example of such files can be found on HDRLib: http://hdrlib.com/
  74446. */
  74447. var HDRCubeTexture = /** @class */ (function (_super) {
  74448. __extends(HDRCubeTexture, _super);
  74449. /**
  74450. * Instantiates an HDRTexture from the following parameters.
  74451. *
  74452. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  74453. * @param scene The scene the texture will be used in
  74454. * @param size The cubemap 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.
  74455. * @param noMipmap Forces to not generate the mipmap if true
  74456. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  74457. * @param useInGammaSpace 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)
  74458. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  74459. */
  74460. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  74461. if (noMipmap === void 0) { noMipmap = false; }
  74462. if (generateHarmonics === void 0) { generateHarmonics = true; }
  74463. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  74464. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  74465. if (onLoad === void 0) { onLoad = null; }
  74466. if (onError === void 0) { onError = null; }
  74467. var _this = _super.call(this, scene) || this;
  74468. _this._useInGammaSpace = false;
  74469. _this._generateHarmonics = true;
  74470. _this._isBABYLONPreprocessed = false;
  74471. _this._onLoad = null;
  74472. _this._onError = null;
  74473. /**
  74474. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  74475. */
  74476. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  74477. /**
  74478. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  74479. * This is usefull at run time to apply the good shader.
  74480. */
  74481. _this.isPMREM = false;
  74482. _this._isBlocking = true;
  74483. /**
  74484. * Gets or sets the center of the bounding box associated with the cube texture
  74485. * It must define where the camera used to render the texture was set
  74486. */
  74487. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  74488. if (!url) {
  74489. return _this;
  74490. }
  74491. _this.name = url;
  74492. _this.url = url;
  74493. _this.hasAlpha = false;
  74494. _this.isCube = true;
  74495. _this._textureMatrix = BABYLON.Matrix.Identity();
  74496. _this._onLoad = onLoad;
  74497. _this._onError = onError;
  74498. _this.gammaSpace = false;
  74499. var caps = scene.getEngine().getCaps();
  74500. if (size) {
  74501. _this._isBABYLONPreprocessed = false;
  74502. _this._noMipmap = noMipmap;
  74503. _this._size = size;
  74504. _this._useInGammaSpace = useInGammaSpace;
  74505. _this._usePMREMGenerator = usePMREMGenerator &&
  74506. caps.textureLOD &&
  74507. caps.textureFloat &&
  74508. !_this._useInGammaSpace;
  74509. }
  74510. else {
  74511. _this._isBABYLONPreprocessed = true;
  74512. _this._noMipmap = false;
  74513. _this._useInGammaSpace = false;
  74514. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  74515. !_this._useInGammaSpace;
  74516. }
  74517. _this.isPMREM = _this._usePMREMGenerator;
  74518. _this._texture = _this._getFromCache(url, _this._noMipmap);
  74519. if (!_this._texture) {
  74520. if (!scene.useDelayedTextureLoading) {
  74521. _this.loadTexture();
  74522. }
  74523. else {
  74524. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  74525. }
  74526. }
  74527. return _this;
  74528. }
  74529. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  74530. /**
  74531. * Gets wether or not the texture is blocking during loading.
  74532. */
  74533. get: function () {
  74534. return this._isBlocking;
  74535. },
  74536. /**
  74537. * Sets wether or not the texture is blocking during loading.
  74538. */
  74539. set: function (value) {
  74540. this._isBlocking = value;
  74541. },
  74542. enumerable: true,
  74543. configurable: true
  74544. });
  74545. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  74546. get: function () {
  74547. return this._boundingBoxSize;
  74548. },
  74549. /**
  74550. * Gets or sets the size of the bounding box associated with the cube texture
  74551. * When defined, the cubemap will switch to local mode
  74552. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  74553. * @example https://www.babylonjs-playground.com/#RNASML
  74554. */
  74555. set: function (value) {
  74556. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  74557. return;
  74558. }
  74559. this._boundingBoxSize = value;
  74560. var scene = this.getScene();
  74561. if (scene) {
  74562. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  74563. }
  74564. },
  74565. enumerable: true,
  74566. configurable: true
  74567. });
  74568. /**
  74569. * Occurs when the file is a preprocessed .babylon.hdr file.
  74570. */
  74571. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  74572. var _this = this;
  74573. var mipLevels = 0;
  74574. var floatArrayView = null;
  74575. var scene = this.getScene();
  74576. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  74577. var mips = new Array();
  74578. if (!floatArrayView) {
  74579. return mips;
  74580. }
  74581. var startIndex = 30;
  74582. for (var level = 0; level < mipLevels; level++) {
  74583. mips.push([]);
  74584. // Fill each pixel of the mip level.
  74585. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  74586. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74587. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  74588. mips[level].push(faceData);
  74589. startIndex += faceSize;
  74590. }
  74591. }
  74592. return mips;
  74593. } : null;
  74594. var callback = function (buffer) {
  74595. var scene = _this.getScene();
  74596. if (!scene) {
  74597. return null;
  74598. }
  74599. // Create Native Array Views
  74600. var intArrayView = new Int32Array(buffer);
  74601. floatArrayView = new Float32Array(buffer);
  74602. // Fill header.
  74603. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  74604. _this._size = intArrayView[1]; // CubeMap max mip face size.
  74605. // Update Texture Information.
  74606. if (!_this._texture) {
  74607. return null;
  74608. }
  74609. _this._texture.updateSize(_this._size, _this._size);
  74610. // Fill polynomial information.
  74611. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  74612. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  74613. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  74614. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  74615. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  74616. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  74617. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  74618. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  74619. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  74620. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  74621. _this.sphericalPolynomial = sphericalPolynomial;
  74622. // Fill pixel data.
  74623. mipLevels = intArrayView[29]; // Number of mip levels.
  74624. var startIndex = 30;
  74625. var data = [];
  74626. var faceSize = Math.pow(_this._size, 2) * 3;
  74627. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74628. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  74629. startIndex += faceSize;
  74630. }
  74631. var results = [];
  74632. var byteArray = null;
  74633. // Push each faces.
  74634. for (var k = 0; k < 6; k++) {
  74635. var dataFace = null;
  74636. // To be deprecated.
  74637. if (version === 1) {
  74638. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  74639. dataFace = data[j];
  74640. }
  74641. // If special cases.
  74642. if (!mipmapGenerator && dataFace) {
  74643. if (!scene.getEngine().getCaps().textureFloat) {
  74644. // 3 channels of 1 bytes per pixel in bytes.
  74645. var byteBuffer = new ArrayBuffer(faceSize);
  74646. byteArray = new Uint8Array(byteBuffer);
  74647. }
  74648. for (var i = 0; i < _this._size * _this._size; i++) {
  74649. // Put in gamma space if requested.
  74650. if (_this._useInGammaSpace) {
  74651. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  74652. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  74653. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  74654. }
  74655. // Convert to int texture for fallback.
  74656. if (byteArray) {
  74657. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  74658. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  74659. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  74660. // May use luminance instead if the result is not accurate.
  74661. var max = Math.max(Math.max(r, g), b);
  74662. if (max > 255) {
  74663. var scale = 255 / max;
  74664. r *= scale;
  74665. g *= scale;
  74666. b *= scale;
  74667. }
  74668. byteArray[(i * 3) + 0] = r;
  74669. byteArray[(i * 3) + 1] = g;
  74670. byteArray[(i * 3) + 2] = b;
  74671. }
  74672. }
  74673. }
  74674. // Fill the array accordingly.
  74675. if (byteArray) {
  74676. results.push(byteArray);
  74677. }
  74678. else {
  74679. results.push(dataFace);
  74680. }
  74681. }
  74682. return results;
  74683. };
  74684. if (scene) {
  74685. 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, mipmapGenerator, this._onLoad, this._onError);
  74686. }
  74687. };
  74688. /**
  74689. * Occurs when the file is raw .hdr file.
  74690. */
  74691. HDRCubeTexture.prototype.loadHDRTexture = function () {
  74692. var _this = this;
  74693. var callback = function (buffer) {
  74694. var scene = _this.getScene();
  74695. if (!scene) {
  74696. return null;
  74697. }
  74698. // Extract the raw linear data.
  74699. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  74700. // Generate harmonics if needed.
  74701. if (_this._generateHarmonics) {
  74702. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  74703. _this.sphericalPolynomial = sphericalPolynomial;
  74704. }
  74705. var results = [];
  74706. var byteArray = null;
  74707. // Push each faces.
  74708. for (var j = 0; j < 6; j++) {
  74709. // Create uintarray fallback.
  74710. if (!scene.getEngine().getCaps().textureFloat) {
  74711. // 3 channels of 1 bytes per pixel in bytes.
  74712. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  74713. byteArray = new Uint8Array(byteBuffer);
  74714. }
  74715. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  74716. // If special cases.
  74717. if (_this._useInGammaSpace || byteArray) {
  74718. for (var i = 0; i < _this._size * _this._size; i++) {
  74719. // Put in gamma space if requested.
  74720. if (_this._useInGammaSpace) {
  74721. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  74722. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  74723. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  74724. }
  74725. // Convert to int texture for fallback.
  74726. if (byteArray) {
  74727. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  74728. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  74729. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  74730. // May use luminance instead if the result is not accurate.
  74731. var max = Math.max(Math.max(r, g), b);
  74732. if (max > 255) {
  74733. var scale = 255 / max;
  74734. r *= scale;
  74735. g *= scale;
  74736. b *= scale;
  74737. }
  74738. byteArray[(i * 3) + 0] = r;
  74739. byteArray[(i * 3) + 1] = g;
  74740. byteArray[(i * 3) + 2] = b;
  74741. }
  74742. }
  74743. }
  74744. if (byteArray) {
  74745. results.push(byteArray);
  74746. }
  74747. else {
  74748. results.push(dataFace);
  74749. }
  74750. }
  74751. return results;
  74752. };
  74753. var mipmapGenerator = null;
  74754. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  74755. // if (!this._noMipmap &&
  74756. // this._usePMREMGenerator) {
  74757. // mipmapGenerator = (data: ArrayBufferView[]) => {
  74758. // // Custom setup of the generator matching with the PBR shader values.
  74759. // var generator = new BABYLON.PMREMGenerator(data,
  74760. // this._size,
  74761. // this._size,
  74762. // 0,
  74763. // 3,
  74764. // this.getScene().getEngine().getCaps().textureFloat,
  74765. // 2048,
  74766. // 0.25,
  74767. // false,
  74768. // true);
  74769. // return generator.filterCubeMap();
  74770. // };
  74771. // }
  74772. var scene = this.getScene();
  74773. if (scene) {
  74774. 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, mipmapGenerator, this._onLoad, this._onError);
  74775. }
  74776. };
  74777. /**
  74778. * Starts the loading process of the texture.
  74779. */
  74780. HDRCubeTexture.prototype.loadTexture = function () {
  74781. if (this._isBABYLONPreprocessed) {
  74782. this.loadBabylonTexture();
  74783. }
  74784. else {
  74785. this.loadHDRTexture();
  74786. }
  74787. };
  74788. HDRCubeTexture.prototype.clone = function () {
  74789. var scene = this.getScene();
  74790. if (!scene) {
  74791. return this;
  74792. }
  74793. var size = (this._isBABYLONPreprocessed ? null : this._size);
  74794. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  74795. // Base texture
  74796. newTexture.level = this.level;
  74797. newTexture.wrapU = this.wrapU;
  74798. newTexture.wrapV = this.wrapV;
  74799. newTexture.coordinatesIndex = this.coordinatesIndex;
  74800. newTexture.coordinatesMode = this.coordinatesMode;
  74801. return newTexture;
  74802. };
  74803. // Methods
  74804. HDRCubeTexture.prototype.delayLoad = function () {
  74805. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  74806. return;
  74807. }
  74808. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  74809. this._texture = this._getFromCache(this.url, this._noMipmap);
  74810. if (!this._texture) {
  74811. this.loadTexture();
  74812. }
  74813. };
  74814. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  74815. return this._textureMatrix;
  74816. };
  74817. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  74818. this._textureMatrix = value;
  74819. };
  74820. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  74821. var texture = null;
  74822. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  74823. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  74824. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  74825. texture.name = parsedTexture.name;
  74826. texture.hasAlpha = parsedTexture.hasAlpha;
  74827. texture.level = parsedTexture.level;
  74828. texture.coordinatesMode = parsedTexture.coordinatesMode;
  74829. texture.isBlocking = parsedTexture.isBlocking;
  74830. }
  74831. if (texture) {
  74832. if (parsedTexture.boundingBoxPosition) {
  74833. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  74834. }
  74835. if (parsedTexture.boundingBoxSize) {
  74836. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  74837. }
  74838. }
  74839. return texture;
  74840. };
  74841. HDRCubeTexture.prototype.serialize = function () {
  74842. if (!this.name) {
  74843. return null;
  74844. }
  74845. var serializationObject = {};
  74846. serializationObject.name = this.name;
  74847. serializationObject.hasAlpha = this.hasAlpha;
  74848. serializationObject.isCube = true;
  74849. serializationObject.level = this.level;
  74850. serializationObject.size = this._size;
  74851. serializationObject.coordinatesMode = this.coordinatesMode;
  74852. serializationObject.useInGammaSpace = this._useInGammaSpace;
  74853. serializationObject.generateHarmonics = this._generateHarmonics;
  74854. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  74855. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  74856. serializationObject.customType = "BABYLON.HDRCubeTexture";
  74857. serializationObject.noMipmap = this._noMipmap;
  74858. serializationObject.isBlocking = this._isBlocking;
  74859. return serializationObject;
  74860. };
  74861. /**
  74862. * Saves as a file the data contained in the texture in a binary format.
  74863. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  74864. * as the spherical used in the lighting.
  74865. * @param url The HDR file url.
  74866. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  74867. * @param onError Method called if any error happens during download.
  74868. * @return The packed binary data.
  74869. */
  74870. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  74871. if (onError === void 0) { onError = null; }
  74872. var callback = function (buffer) {
  74873. var data = new Blob([buffer], { type: 'application/octet-stream' });
  74874. // Returns a URL you can use as a href.
  74875. var objUrl = window.URL.createObjectURL(data);
  74876. // Simulates a link to it and click to dowload.
  74877. var a = document.createElement("a");
  74878. document.body.appendChild(a);
  74879. a.style.display = "none";
  74880. a.href = objUrl;
  74881. a.download = "envmap.babylon.hdr";
  74882. a.click();
  74883. };
  74884. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  74885. };
  74886. /**
  74887. * Serializes the data contained in the texture in a binary format.
  74888. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  74889. * as the spherical used in the lighting.
  74890. * @param url The HDR file url.
  74891. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  74892. * @param onError Method called if any error happens during download.
  74893. * @return The packed binary data.
  74894. */
  74895. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  74896. if (onError === void 0) { onError = null; }
  74897. // Needs the url tho create the texture.
  74898. if (!url) {
  74899. return;
  74900. }
  74901. // Check Power of two size.
  74902. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  74903. return;
  74904. }
  74905. // Coming Back in 3.x.
  74906. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  74907. };
  74908. HDRCubeTexture._facesMapping = [
  74909. "right",
  74910. "left",
  74911. "up",
  74912. "down",
  74913. "front",
  74914. "back"
  74915. ];
  74916. return HDRCubeTexture;
  74917. }(BABYLON.BaseTexture));
  74918. BABYLON.HDRCubeTexture = HDRCubeTexture;
  74919. })(BABYLON || (BABYLON = {}));
  74920. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  74921. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  74922. // Huge respect for a such great lib.
  74923. // Earcut license:
  74924. // Copyright (c) 2016, Mapbox
  74925. //
  74926. // Permission to use, copy, modify, and/or distribute this software for any purpose
  74927. // with or without fee is hereby granted, provided that the above copyright notice
  74928. // and this permission notice appear in all copies.
  74929. //
  74930. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  74931. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  74932. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  74933. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  74934. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  74935. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  74936. // THIS SOFTWARE.
  74937. var Earcut;
  74938. (function (Earcut) {
  74939. /**
  74940. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  74941. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  74942. * @param holeIndices is an array of hole indices if any (e.g. [5, 8] for a 12- vertice input would mean one hole with vertices 5–7 and another with 8–11).
  74943. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  74944. */
  74945. function earcut(data, holeIndices, dim) {
  74946. dim = dim || 2;
  74947. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  74948. if (!outerNode)
  74949. return triangles;
  74950. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  74951. if (hasHoles)
  74952. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  74953. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  74954. if (data.length > 80 * dim) {
  74955. minX = maxX = data[0];
  74956. minY = maxY = data[1];
  74957. for (var i = dim; i < outerLen; i += dim) {
  74958. x = data[i];
  74959. y = data[i + 1];
  74960. if (x < minX)
  74961. minX = x;
  74962. if (y < minY)
  74963. minY = y;
  74964. if (x > maxX)
  74965. maxX = x;
  74966. if (y > maxY)
  74967. maxY = y;
  74968. }
  74969. // minX, minY and size are later used to transform coords into integers for z-order calculation
  74970. size = Math.max(maxX - minX, maxY - minY);
  74971. }
  74972. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  74973. return triangles;
  74974. }
  74975. Earcut.earcut = earcut;
  74976. var Node = /** @class */ (function () {
  74977. function Node(i, x, y) {
  74978. this.i = i;
  74979. this.x = x;
  74980. this.y = y;
  74981. this.prev = null;
  74982. this.next = null;
  74983. this.z = null;
  74984. this.prevZ = null;
  74985. this.nextZ = null;
  74986. this.steiner = false;
  74987. }
  74988. return Node;
  74989. }());
  74990. // create a circular doubly linked list from polygon points in the specified winding order
  74991. function linkedList(data, start, end, dim, clockwise) {
  74992. var i, last = null;
  74993. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  74994. for (i = start; i < end; i += dim)
  74995. last = insertNode(i, data[i], data[i + 1], last);
  74996. }
  74997. else {
  74998. for (i = end - dim; i >= start; i -= dim)
  74999. last = insertNode(i, data[i], data[i + 1], last);
  75000. }
  75001. if (last && equals(last, last.next)) {
  75002. removeNode(last);
  75003. last = last.next;
  75004. }
  75005. return last;
  75006. }
  75007. // eliminate colinear or duplicate points
  75008. function filterPoints(start, end) {
  75009. if (!start)
  75010. return start;
  75011. if (!end)
  75012. end = start;
  75013. var p = start, again;
  75014. do {
  75015. again = false;
  75016. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  75017. removeNode(p);
  75018. p = end = p.prev;
  75019. if (p === p.next)
  75020. return undefined;
  75021. again = true;
  75022. }
  75023. else {
  75024. p = p.next;
  75025. }
  75026. } while (again || p !== end);
  75027. return end;
  75028. }
  75029. // main ear slicing loop which triangulates a polygon (given as a linked list)
  75030. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  75031. if (!ear)
  75032. return;
  75033. // interlink polygon nodes in z-order
  75034. if (!pass && size)
  75035. indexCurve(ear, minX, minY, size);
  75036. var stop = ear, prev, next;
  75037. // iterate through ears, slicing them one by one
  75038. while (ear.prev !== ear.next) {
  75039. prev = ear.prev;
  75040. next = ear.next;
  75041. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  75042. // cut off the triangle
  75043. triangles.push(prev.i / dim);
  75044. triangles.push(ear.i / dim);
  75045. triangles.push(next.i / dim);
  75046. removeNode(ear);
  75047. // skipping the next vertice leads to less sliver triangles
  75048. ear = next.next;
  75049. stop = next.next;
  75050. continue;
  75051. }
  75052. ear = next;
  75053. // if we looped through the whole remaining polygon and can't find any more ears
  75054. if (ear === stop) {
  75055. // try filtering points and slicing again
  75056. if (!pass) {
  75057. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  75058. // if this didn't work, try curing all small self-intersections locally
  75059. }
  75060. else if (pass === 1) {
  75061. ear = cureLocalIntersections(ear, triangles, dim);
  75062. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  75063. // as a last resort, try splitting the remaining polygon into two
  75064. }
  75065. else if (pass === 2) {
  75066. splitEarcut(ear, triangles, dim, minX, minY, size);
  75067. }
  75068. break;
  75069. }
  75070. }
  75071. }
  75072. // check whether a polygon node forms a valid ear with adjacent nodes
  75073. function isEar(ear) {
  75074. var a = ear.prev, b = ear, c = ear.next;
  75075. if (area(a, b, c) >= 0)
  75076. return false; // reflex, can't be an ear
  75077. // now make sure we don't have other points inside the potential ear
  75078. var p = ear.next.next;
  75079. while (p !== ear.prev) {
  75080. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  75081. area(p.prev, p, p.next) >= 0)
  75082. return false;
  75083. p = p.next;
  75084. }
  75085. return true;
  75086. }
  75087. function isEarHashed(ear, minX, minY, size) {
  75088. var a = ear.prev, b = ear, c = ear.next;
  75089. if (area(a, b, c) >= 0)
  75090. return false; // reflex, can't be an ear
  75091. // triangle bbox; min & max are calculated like this for speed
  75092. var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
  75093. // z-order range for the current triangle bbox;
  75094. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  75095. // first look for points inside the triangle in increasing z-order
  75096. var p = ear.nextZ;
  75097. while (p && p.z <= maxZ) {
  75098. if (p !== ear.prev &&
  75099. p !== ear.next &&
  75100. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  75101. area(p.prev, p, p.next) >= 0)
  75102. return false;
  75103. p = p.nextZ;
  75104. }
  75105. // then look for points in decreasing z-order
  75106. p = ear.prevZ;
  75107. while (p && p.z >= minZ) {
  75108. if (p !== ear.prev &&
  75109. p !== ear.next &&
  75110. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  75111. area(p.prev, p, p.next) >= 0)
  75112. return false;
  75113. p = p.prevZ;
  75114. }
  75115. return true;
  75116. }
  75117. // go through all polygon nodes and cure small local self-intersections
  75118. function cureLocalIntersections(start, triangles, dim) {
  75119. var p = start;
  75120. do {
  75121. var a = p.prev, b = p.next.next;
  75122. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  75123. triangles.push(a.i / dim);
  75124. triangles.push(p.i / dim);
  75125. triangles.push(b.i / dim);
  75126. // remove two nodes involved
  75127. removeNode(p);
  75128. removeNode(p.next);
  75129. p = start = b;
  75130. }
  75131. p = p.next;
  75132. } while (p !== start);
  75133. return p;
  75134. }
  75135. // try splitting polygon into two and triangulate them independently
  75136. function splitEarcut(start, triangles, dim, minX, minY, size) {
  75137. // look for a valid diagonal that divides the polygon into two
  75138. var a = start;
  75139. do {
  75140. var b = a.next.next;
  75141. while (b !== a.prev) {
  75142. if (a.i !== b.i && isValidDiagonal(a, b)) {
  75143. // split the polygon in two by the diagonal
  75144. var c = splitPolygon(a, b);
  75145. // filter colinear points around the cuts
  75146. a = filterPoints(a, a.next);
  75147. c = filterPoints(c, c.next);
  75148. // run earcut on each half
  75149. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  75150. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  75151. return;
  75152. }
  75153. b = b.next;
  75154. }
  75155. a = a.next;
  75156. } while (a !== start);
  75157. }
  75158. // link every hole into the outer loop, producing a single-ring polygon without holes
  75159. function eliminateHoles(data, holeIndices, outerNode, dim) {
  75160. var queue = [], i, len, start, end, list;
  75161. for (i = 0, len = holeIndices.length; i < len; i++) {
  75162. start = holeIndices[i] * dim;
  75163. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  75164. list = linkedList(data, start, end, dim, false);
  75165. if (list === list.next)
  75166. list.steiner = true;
  75167. queue.push(getLeftmost(list));
  75168. }
  75169. queue.sort(compareX);
  75170. // process holes from left to right
  75171. for (i = 0; i < queue.length; i++) {
  75172. eliminateHole(queue[i], outerNode);
  75173. outerNode = filterPoints(outerNode, outerNode.next);
  75174. }
  75175. return outerNode;
  75176. }
  75177. function compareX(a, b) {
  75178. return a.x - b.x;
  75179. }
  75180. // find a bridge between vertices that connects hole with an outer ring and and link it
  75181. function eliminateHole(hole, outerNode) {
  75182. outerNode = findHoleBridge(hole, outerNode);
  75183. if (outerNode) {
  75184. var b = splitPolygon(outerNode, hole);
  75185. filterPoints(b, b.next);
  75186. }
  75187. }
  75188. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  75189. function findHoleBridge(hole, outerNode) {
  75190. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  75191. // find a segment intersected by a ray from the hole's leftmost point to the left;
  75192. // segment's endpoint with lesser x will be potential connection point
  75193. do {
  75194. if (hy <= p.y && hy >= p.next.y) {
  75195. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  75196. if (x <= hx && x > qx) {
  75197. qx = x;
  75198. if (x === hx) {
  75199. if (hy === p.y)
  75200. return p;
  75201. if (hy === p.next.y)
  75202. return p.next;
  75203. }
  75204. m = p.x < p.next.x ? p : p.next;
  75205. }
  75206. }
  75207. p = p.next;
  75208. } while (p !== outerNode);
  75209. if (!m)
  75210. return null;
  75211. if (hx === qx)
  75212. return m.prev; // hole touches outer segment; pick lower endpoint
  75213. // look for points inside the triangle of hole point, segment intersection and endpoint;
  75214. // if there are no points found, we have a valid connection;
  75215. // otherwise choose the point of the minimum angle with the ray as connection point
  75216. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  75217. p = m.next;
  75218. while (p !== stop) {
  75219. if (hx >= p.x &&
  75220. p.x >= mx &&
  75221. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  75222. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  75223. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  75224. m = p;
  75225. tanMin = tan;
  75226. }
  75227. }
  75228. p = p.next;
  75229. }
  75230. return m;
  75231. }
  75232. // interlink polygon nodes in z-order
  75233. function indexCurve(start, minX, minY, size) {
  75234. var p = start;
  75235. do {
  75236. if (p.z === null)
  75237. p.z = zOrder(p.x, p.y, minX, minY, size);
  75238. p.prevZ = p.prev;
  75239. p.nextZ = p.next;
  75240. p = p.next;
  75241. } while (p !== start);
  75242. p.prevZ.nextZ = null;
  75243. p.prevZ = null;
  75244. sortLinked(p);
  75245. }
  75246. // Simon Tatham's linked list merge sort algorithm
  75247. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  75248. function sortLinked(list) {
  75249. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  75250. do {
  75251. p = list;
  75252. list = null;
  75253. tail = null;
  75254. numMerges = 0;
  75255. while (p) {
  75256. numMerges++;
  75257. q = p;
  75258. pSize = 0;
  75259. for (i = 0; i < inSize; i++) {
  75260. pSize++;
  75261. q = q.nextZ;
  75262. if (!q)
  75263. break;
  75264. }
  75265. qSize = inSize;
  75266. while (pSize > 0 || (qSize > 0 && q)) {
  75267. if (pSize === 0) {
  75268. e = q;
  75269. q = q.nextZ;
  75270. qSize--;
  75271. }
  75272. else if (qSize === 0 || !q) {
  75273. e = p;
  75274. p = p.nextZ;
  75275. pSize--;
  75276. }
  75277. else if (p.z <= q.z) {
  75278. e = p;
  75279. p = p.nextZ;
  75280. pSize--;
  75281. }
  75282. else {
  75283. e = q;
  75284. q = q.nextZ;
  75285. qSize--;
  75286. }
  75287. if (tail)
  75288. tail.nextZ = e;
  75289. else
  75290. list = e;
  75291. e.prevZ = tail;
  75292. tail = e;
  75293. }
  75294. p = q;
  75295. }
  75296. tail.nextZ = null;
  75297. inSize *= 2;
  75298. } while (numMerges > 1);
  75299. return list;
  75300. }
  75301. // z-order of a point given coords and size of the data bounding box
  75302. function zOrder(x, y, minX, minY, size) {
  75303. // coords are transformed into non-negative 15-bit integer range
  75304. x = 32767 * (x - minX) / size;
  75305. y = 32767 * (y - minY) / size;
  75306. x = (x | (x << 8)) & 0x00FF00FF;
  75307. x = (x | (x << 4)) & 0x0F0F0F0F;
  75308. x = (x | (x << 2)) & 0x33333333;
  75309. x = (x | (x << 1)) & 0x55555555;
  75310. y = (y | (y << 8)) & 0x00FF00FF;
  75311. y = (y | (y << 4)) & 0x0F0F0F0F;
  75312. y = (y | (y << 2)) & 0x33333333;
  75313. y = (y | (y << 1)) & 0x55555555;
  75314. return x | (y << 1);
  75315. }
  75316. // find the leftmost node of a polygon ring
  75317. function getLeftmost(start) {
  75318. var p = start, leftmost = start;
  75319. do {
  75320. if (p.x < leftmost.x)
  75321. leftmost = p;
  75322. p = p.next;
  75323. } while (p !== start);
  75324. return leftmost;
  75325. }
  75326. // check if a point lies within a convex triangle
  75327. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  75328. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  75329. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  75330. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  75331. }
  75332. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  75333. function isValidDiagonal(a, b) {
  75334. return a.next.i !== b.i &&
  75335. a.prev.i !== b.i &&
  75336. !intersectsPolygon(a, b) &&
  75337. locallyInside(a, b) &&
  75338. locallyInside(b, a) &&
  75339. middleInside(a, b);
  75340. }
  75341. // signed area of a triangle
  75342. function area(p, q, r) {
  75343. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  75344. }
  75345. // check if two points are equal
  75346. function equals(p1, p2) {
  75347. return p1.x === p2.x && p1.y === p2.y;
  75348. }
  75349. // check if two segments intersect
  75350. function intersects(p1, q1, p2, q2) {
  75351. if ((equals(p1, q1) && equals(p2, q2)) ||
  75352. (equals(p1, q2) && equals(p2, q1)))
  75353. return true;
  75354. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  75355. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  75356. }
  75357. // check if a polygon diagonal intersects any polygon segments
  75358. function intersectsPolygon(a, b) {
  75359. var p = a;
  75360. do {
  75361. if (p.i !== a.i &&
  75362. p.next.i !== a.i &&
  75363. p.i !== b.i &&
  75364. p.next.i !== b.i &&
  75365. intersects(p, p.next, a, b))
  75366. return true;
  75367. p = p.next;
  75368. } while (p !== a);
  75369. return false;
  75370. }
  75371. // check if a polygon diagonal is locally inside the polygon
  75372. function locallyInside(a, b) {
  75373. return area(a.prev, a, a.next) < 0
  75374. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  75375. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  75376. }
  75377. // check if the middle point of a polygon diagonal is inside the polygon
  75378. function middleInside(a, b) {
  75379. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  75380. do {
  75381. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  75382. inside = !inside;
  75383. p = p.next;
  75384. } while (p !== a);
  75385. return inside;
  75386. }
  75387. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  75388. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  75389. function splitPolygon(a, b) {
  75390. var a2 = new Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev;
  75391. a.next = b;
  75392. b.prev = a;
  75393. a2.next = an;
  75394. an.prev = a2;
  75395. b2.next = a2;
  75396. a2.prev = b2;
  75397. bp.next = b2;
  75398. b2.prev = bp;
  75399. return b2;
  75400. }
  75401. // create a node and optionally link it with previous one (in a circular doubly linked list)
  75402. function insertNode(i, x, y, last) {
  75403. var p = new Node(i, x, y);
  75404. if (!last) {
  75405. p.prev = p;
  75406. p.next = p;
  75407. }
  75408. else {
  75409. p.next = last.next;
  75410. p.prev = last;
  75411. last.next.prev = p;
  75412. last.next = p;
  75413. }
  75414. return p;
  75415. }
  75416. function removeNode(p) {
  75417. p.next.prev = p.prev;
  75418. p.prev.next = p.next;
  75419. if (p.prevZ)
  75420. p.prevZ.nextZ = p.nextZ;
  75421. if (p.nextZ)
  75422. p.nextZ.prevZ = p.prevZ;
  75423. }
  75424. /**
  75425. * return a percentage difference between the polygon area and its triangulation area;
  75426. * used to verify correctness of triangulation
  75427. */
  75428. function deviation(data, holeIndices, dim, triangles) {
  75429. var hasHoles = holeIndices && holeIndices.length;
  75430. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  75431. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  75432. if (hasHoles) {
  75433. for (var i = 0, len = holeIndices.length; i < len; i++) {
  75434. var start = holeIndices[i] * dim;
  75435. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  75436. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  75437. }
  75438. }
  75439. var trianglesArea = 0;
  75440. for (i = 0; i < triangles.length; i += 3) {
  75441. var a = triangles[i] * dim;
  75442. var b = triangles[i + 1] * dim;
  75443. var c = triangles[i + 2] * dim;
  75444. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  75445. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  75446. }
  75447. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  75448. }
  75449. Earcut.deviation = deviation;
  75450. ;
  75451. function signedArea(data, start, end, dim) {
  75452. var sum = 0;
  75453. for (var i = start, j = end - dim; i < end; i += dim) {
  75454. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  75455. j = i;
  75456. }
  75457. return sum;
  75458. }
  75459. /**
  75460. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  75461. */
  75462. function flatten(data) {
  75463. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  75464. for (var i = 0; i < data.length; i++) {
  75465. for (var j = 0; j < data[i].length; j++) {
  75466. for (var d = 0; d < dim; d++)
  75467. result.vertices.push(data[i][j][d]);
  75468. }
  75469. if (i > 0) {
  75470. holeIndex += data[i - 1].length;
  75471. result.holes.push(holeIndex);
  75472. }
  75473. }
  75474. return result;
  75475. }
  75476. Earcut.flatten = flatten;
  75477. ;
  75478. })(Earcut || (Earcut = {}));
  75479. //# sourceMappingURL=babylon.earcut.js.map
  75480. var BABYLON;
  75481. (function (BABYLON) {
  75482. var IndexedVector2 = /** @class */ (function (_super) {
  75483. __extends(IndexedVector2, _super);
  75484. function IndexedVector2(original, index) {
  75485. var _this = _super.call(this, original.x, original.y) || this;
  75486. _this.index = index;
  75487. return _this;
  75488. }
  75489. return IndexedVector2;
  75490. }(BABYLON.Vector2));
  75491. var PolygonPoints = /** @class */ (function () {
  75492. function PolygonPoints() {
  75493. this.elements = new Array();
  75494. }
  75495. PolygonPoints.prototype.add = function (originalPoints) {
  75496. var _this = this;
  75497. var result = new Array();
  75498. originalPoints.forEach(function (point) {
  75499. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  75500. var newPoint = new IndexedVector2(point, _this.elements.length);
  75501. result.push(newPoint);
  75502. _this.elements.push(newPoint);
  75503. }
  75504. });
  75505. return result;
  75506. };
  75507. PolygonPoints.prototype.computeBounds = function () {
  75508. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  75509. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  75510. this.elements.forEach(function (point) {
  75511. // x
  75512. if (point.x < lmin.x) {
  75513. lmin.x = point.x;
  75514. }
  75515. else if (point.x > lmax.x) {
  75516. lmax.x = point.x;
  75517. }
  75518. // y
  75519. if (point.y < lmin.y) {
  75520. lmin.y = point.y;
  75521. }
  75522. else if (point.y > lmax.y) {
  75523. lmax.y = point.y;
  75524. }
  75525. });
  75526. return {
  75527. min: lmin,
  75528. max: lmax,
  75529. width: lmax.x - lmin.x,
  75530. height: lmax.y - lmin.y
  75531. };
  75532. };
  75533. return PolygonPoints;
  75534. }());
  75535. var Polygon = /** @class */ (function () {
  75536. function Polygon() {
  75537. }
  75538. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  75539. return [
  75540. new BABYLON.Vector2(xmin, ymin),
  75541. new BABYLON.Vector2(xmax, ymin),
  75542. new BABYLON.Vector2(xmax, ymax),
  75543. new BABYLON.Vector2(xmin, ymax)
  75544. ];
  75545. };
  75546. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  75547. if (cx === void 0) { cx = 0; }
  75548. if (cy === void 0) { cy = 0; }
  75549. if (numberOfSides === void 0) { numberOfSides = 32; }
  75550. var result = new Array();
  75551. var angle = 0;
  75552. var increment = (Math.PI * 2) / numberOfSides;
  75553. for (var i = 0; i < numberOfSides; i++) {
  75554. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  75555. angle -= increment;
  75556. }
  75557. return result;
  75558. };
  75559. Polygon.Parse = function (input) {
  75560. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  75561. var i, result = [];
  75562. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  75563. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  75564. }
  75565. return result;
  75566. };
  75567. Polygon.StartingAt = function (x, y) {
  75568. return BABYLON.Path2.StartingAt(x, y);
  75569. };
  75570. return Polygon;
  75571. }());
  75572. BABYLON.Polygon = Polygon;
  75573. var PolygonMeshBuilder = /** @class */ (function () {
  75574. function PolygonMeshBuilder(name, contours, scene) {
  75575. this._points = new PolygonPoints();
  75576. this._outlinepoints = new PolygonPoints();
  75577. this._holes = new Array();
  75578. this._epoints = new Array();
  75579. this._eholes = new Array();
  75580. this._name = name;
  75581. this._scene = scene;
  75582. var points;
  75583. if (contours instanceof BABYLON.Path2) {
  75584. points = contours.getPoints();
  75585. }
  75586. else {
  75587. points = contours;
  75588. }
  75589. this._addToepoint(points);
  75590. this._points.add(points);
  75591. this._outlinepoints.add(points);
  75592. }
  75593. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  75594. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  75595. var p = points_1[_i];
  75596. this._epoints.push(p.x, p.y);
  75597. }
  75598. };
  75599. PolygonMeshBuilder.prototype.addHole = function (hole) {
  75600. this._points.add(hole);
  75601. var holepoints = new PolygonPoints();
  75602. holepoints.add(hole);
  75603. this._holes.push(holepoints);
  75604. this._eholes.push(this._epoints.length / 2);
  75605. this._addToepoint(hole);
  75606. return this;
  75607. };
  75608. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  75609. var _this = this;
  75610. if (updatable === void 0) { updatable = false; }
  75611. if (depth === void 0) { depth = 0; }
  75612. var result = new BABYLON.Mesh(this._name, this._scene);
  75613. var normals = new Array();
  75614. var positions = new Array();
  75615. var uvs = new Array();
  75616. var bounds = this._points.computeBounds();
  75617. this._points.elements.forEach(function (p) {
  75618. normals.push(0, 1.0, 0);
  75619. positions.push(p.x, 0, p.y);
  75620. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  75621. });
  75622. var indices = new Array();
  75623. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  75624. for (var i = 0; i < res.length; i++) {
  75625. indices.push(res[i]);
  75626. }
  75627. if (depth > 0) {
  75628. var positionscount = (positions.length / 3); //get the current pointcount
  75629. this._points.elements.forEach(function (p) {
  75630. normals.push(0, -1.0, 0);
  75631. positions.push(p.x, -depth, p.y);
  75632. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  75633. });
  75634. var totalCount = indices.length;
  75635. for (var i = 0; i < totalCount; i += 3) {
  75636. var i0 = indices[i + 0];
  75637. var i1 = indices[i + 1];
  75638. var i2 = indices[i + 2];
  75639. indices.push(i2 + positionscount);
  75640. indices.push(i1 + positionscount);
  75641. indices.push(i0 + positionscount);
  75642. }
  75643. //Add the sides
  75644. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  75645. this._holes.forEach(function (hole) {
  75646. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  75647. });
  75648. }
  75649. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  75650. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  75651. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  75652. result.setIndices(indices);
  75653. return result;
  75654. };
  75655. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  75656. var StartIndex = positions.length / 3;
  75657. var ulength = 0;
  75658. for (var i = 0; i < points.elements.length; i++) {
  75659. var p = points.elements[i];
  75660. var p1;
  75661. if ((i + 1) > points.elements.length - 1) {
  75662. p1 = points.elements[0];
  75663. }
  75664. else {
  75665. p1 = points.elements[i + 1];
  75666. }
  75667. positions.push(p.x, 0, p.y);
  75668. positions.push(p.x, -depth, p.y);
  75669. positions.push(p1.x, 0, p1.y);
  75670. positions.push(p1.x, -depth, p1.y);
  75671. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  75672. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  75673. var v3 = v2.subtract(v1);
  75674. var v4 = new BABYLON.Vector3(0, 1, 0);
  75675. var vn = BABYLON.Vector3.Cross(v3, v4);
  75676. vn = vn.normalize();
  75677. uvs.push(ulength / bounds.width, 0);
  75678. uvs.push(ulength / bounds.width, 1);
  75679. ulength += v3.length();
  75680. uvs.push((ulength / bounds.width), 0);
  75681. uvs.push((ulength / bounds.width), 1);
  75682. if (!flip) {
  75683. normals.push(-vn.x, -vn.y, -vn.z);
  75684. normals.push(-vn.x, -vn.y, -vn.z);
  75685. normals.push(-vn.x, -vn.y, -vn.z);
  75686. normals.push(-vn.x, -vn.y, -vn.z);
  75687. indices.push(StartIndex);
  75688. indices.push(StartIndex + 1);
  75689. indices.push(StartIndex + 2);
  75690. indices.push(StartIndex + 1);
  75691. indices.push(StartIndex + 3);
  75692. indices.push(StartIndex + 2);
  75693. }
  75694. else {
  75695. normals.push(vn.x, vn.y, vn.z);
  75696. normals.push(vn.x, vn.y, vn.z);
  75697. normals.push(vn.x, vn.y, vn.z);
  75698. normals.push(vn.x, vn.y, vn.z);
  75699. indices.push(StartIndex);
  75700. indices.push(StartIndex + 2);
  75701. indices.push(StartIndex + 1);
  75702. indices.push(StartIndex + 1);
  75703. indices.push(StartIndex + 2);
  75704. indices.push(StartIndex + 3);
  75705. }
  75706. StartIndex += 4;
  75707. }
  75708. ;
  75709. };
  75710. return PolygonMeshBuilder;
  75711. }());
  75712. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  75713. })(BABYLON || (BABYLON = {}));
  75714. //# sourceMappingURL=babylon.polygonMesh.js.map
  75715. var BABYLON;
  75716. (function (BABYLON) {
  75717. // Unique ID when we import meshes from Babylon to CSG
  75718. var currentCSGMeshId = 0;
  75719. // # class Vertex
  75720. // Represents a vertex of a polygon. Use your own vertex class instead of this
  75721. // one to provide additional features like texture coordinates and vertex
  75722. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  75723. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  75724. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  75725. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  75726. // is not used anywhere else.
  75727. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  75728. var Vertex = /** @class */ (function () {
  75729. function Vertex(pos, normal, uv) {
  75730. this.pos = pos;
  75731. this.normal = normal;
  75732. this.uv = uv;
  75733. }
  75734. Vertex.prototype.clone = function () {
  75735. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  75736. };
  75737. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  75738. // orientation of a polygon is flipped.
  75739. Vertex.prototype.flip = function () {
  75740. this.normal = this.normal.scale(-1);
  75741. };
  75742. // Create a new vertex between this vertex and `other` by linearly
  75743. // interpolating all properties using a parameter of `t`. Subclasses should
  75744. // override this to interpolate additional properties.
  75745. Vertex.prototype.interpolate = function (other, t) {
  75746. 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));
  75747. };
  75748. return Vertex;
  75749. }());
  75750. // # class Plane
  75751. // Represents a plane in 3D space.
  75752. var Plane = /** @class */ (function () {
  75753. function Plane(normal, w) {
  75754. this.normal = normal;
  75755. this.w = w;
  75756. }
  75757. Plane.FromPoints = function (a, b, c) {
  75758. var v0 = c.subtract(a);
  75759. var v1 = b.subtract(a);
  75760. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  75761. return null;
  75762. }
  75763. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  75764. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  75765. };
  75766. Plane.prototype.clone = function () {
  75767. return new Plane(this.normal.clone(), this.w);
  75768. };
  75769. Plane.prototype.flip = function () {
  75770. this.normal.scaleInPlace(-1);
  75771. this.w = -this.w;
  75772. };
  75773. // Split `polygon` by this plane if needed, then put the polygon or polygon
  75774. // fragments in the appropriate lists. Coplanar polygons go into either
  75775. // `coplanarFront` or `coplanarBack` depending on their orientation with
  75776. // respect to this plane. Polygons in front or in back of this plane go into
  75777. // either `front` or `back`.
  75778. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  75779. var COPLANAR = 0;
  75780. var FRONT = 1;
  75781. var BACK = 2;
  75782. var SPANNING = 3;
  75783. // Classify each point as well as the entire polygon into one of the above
  75784. // four classes.
  75785. var polygonType = 0;
  75786. var types = [];
  75787. var i;
  75788. var t;
  75789. for (i = 0; i < polygon.vertices.length; i++) {
  75790. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  75791. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  75792. polygonType |= type;
  75793. types.push(type);
  75794. }
  75795. // Put the polygon in the correct list, splitting it when necessary.
  75796. switch (polygonType) {
  75797. case COPLANAR:
  75798. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  75799. break;
  75800. case FRONT:
  75801. front.push(polygon);
  75802. break;
  75803. case BACK:
  75804. back.push(polygon);
  75805. break;
  75806. case SPANNING:
  75807. var f = [], b = [];
  75808. for (i = 0; i < polygon.vertices.length; i++) {
  75809. var j = (i + 1) % polygon.vertices.length;
  75810. var ti = types[i], tj = types[j];
  75811. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  75812. if (ti !== BACK)
  75813. f.push(vi);
  75814. if (ti !== FRONT)
  75815. b.push(ti !== BACK ? vi.clone() : vi);
  75816. if ((ti | tj) === SPANNING) {
  75817. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  75818. var v = vi.interpolate(vj, t);
  75819. f.push(v);
  75820. b.push(v.clone());
  75821. }
  75822. }
  75823. var poly;
  75824. if (f.length >= 3) {
  75825. poly = new Polygon(f, polygon.shared);
  75826. if (poly.plane)
  75827. front.push(poly);
  75828. }
  75829. if (b.length >= 3) {
  75830. poly = new Polygon(b, polygon.shared);
  75831. if (poly.plane)
  75832. back.push(poly);
  75833. }
  75834. break;
  75835. }
  75836. };
  75837. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  75838. // point is on the plane.
  75839. Plane.EPSILON = 1e-5;
  75840. return Plane;
  75841. }());
  75842. // # class Polygon
  75843. // Represents a convex polygon. The vertices used to initialize a polygon must
  75844. // be coplanar and form a convex loop.
  75845. //
  75846. // Each convex polygon has a `shared` property, which is shared between all
  75847. // polygons that are clones of each other or were split from the same polygon.
  75848. // This can be used to define per-polygon properties (such as surface color).
  75849. var Polygon = /** @class */ (function () {
  75850. function Polygon(vertices, shared) {
  75851. this.vertices = vertices;
  75852. this.shared = shared;
  75853. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  75854. }
  75855. Polygon.prototype.clone = function () {
  75856. var vertices = this.vertices.map(function (v) { return v.clone(); });
  75857. return new Polygon(vertices, this.shared);
  75858. };
  75859. Polygon.prototype.flip = function () {
  75860. this.vertices.reverse().map(function (v) { v.flip(); });
  75861. this.plane.flip();
  75862. };
  75863. return Polygon;
  75864. }());
  75865. // # class Node
  75866. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  75867. // by picking a polygon to split along. That polygon (and all other coplanar
  75868. // polygons) are added directly to that node and the other polygons are added to
  75869. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  75870. // no distinction between internal and leaf nodes.
  75871. var Node = /** @class */ (function () {
  75872. function Node(polygons) {
  75873. this.plane = null;
  75874. this.front = null;
  75875. this.back = null;
  75876. this.polygons = new Array();
  75877. if (polygons) {
  75878. this.build(polygons);
  75879. }
  75880. }
  75881. Node.prototype.clone = function () {
  75882. var node = new Node();
  75883. node.plane = this.plane && this.plane.clone();
  75884. node.front = this.front && this.front.clone();
  75885. node.back = this.back && this.back.clone();
  75886. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  75887. return node;
  75888. };
  75889. // Convert solid space to empty space and empty space to solid space.
  75890. Node.prototype.invert = function () {
  75891. for (var i = 0; i < this.polygons.length; i++) {
  75892. this.polygons[i].flip();
  75893. }
  75894. if (this.plane) {
  75895. this.plane.flip();
  75896. }
  75897. if (this.front) {
  75898. this.front.invert();
  75899. }
  75900. if (this.back) {
  75901. this.back.invert();
  75902. }
  75903. var temp = this.front;
  75904. this.front = this.back;
  75905. this.back = temp;
  75906. };
  75907. // Recursively remove all polygons in `polygons` that are inside this BSP
  75908. // tree.
  75909. Node.prototype.clipPolygons = function (polygons) {
  75910. if (!this.plane)
  75911. return polygons.slice();
  75912. var front = new Array(), back = new Array();
  75913. for (var i = 0; i < polygons.length; i++) {
  75914. this.plane.splitPolygon(polygons[i], front, back, front, back);
  75915. }
  75916. if (this.front) {
  75917. front = this.front.clipPolygons(front);
  75918. }
  75919. if (this.back) {
  75920. back = this.back.clipPolygons(back);
  75921. }
  75922. else {
  75923. back = [];
  75924. }
  75925. return front.concat(back);
  75926. };
  75927. // Remove all polygons in this BSP tree that are inside the other BSP tree
  75928. // `bsp`.
  75929. Node.prototype.clipTo = function (bsp) {
  75930. this.polygons = bsp.clipPolygons(this.polygons);
  75931. if (this.front)
  75932. this.front.clipTo(bsp);
  75933. if (this.back)
  75934. this.back.clipTo(bsp);
  75935. };
  75936. // Return a list of all polygons in this BSP tree.
  75937. Node.prototype.allPolygons = function () {
  75938. var polygons = this.polygons.slice();
  75939. if (this.front)
  75940. polygons = polygons.concat(this.front.allPolygons());
  75941. if (this.back)
  75942. polygons = polygons.concat(this.back.allPolygons());
  75943. return polygons;
  75944. };
  75945. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  75946. // new polygons are filtered down to the bottom of the tree and become new
  75947. // nodes there. Each set of polygons is partitioned using the first polygon
  75948. // (no heuristic is used to pick a good split).
  75949. Node.prototype.build = function (polygons) {
  75950. if (!polygons.length)
  75951. return;
  75952. if (!this.plane)
  75953. this.plane = polygons[0].plane.clone();
  75954. var front = new Array(), back = new Array();
  75955. for (var i = 0; i < polygons.length; i++) {
  75956. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  75957. }
  75958. if (front.length) {
  75959. if (!this.front)
  75960. this.front = new Node();
  75961. this.front.build(front);
  75962. }
  75963. if (back.length) {
  75964. if (!this.back)
  75965. this.back = new Node();
  75966. this.back.build(back);
  75967. }
  75968. };
  75969. return Node;
  75970. }());
  75971. var CSG = /** @class */ (function () {
  75972. function CSG() {
  75973. this.polygons = new Array();
  75974. }
  75975. // Convert BABYLON.Mesh to BABYLON.CSG
  75976. CSG.FromMesh = function (mesh) {
  75977. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  75978. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  75979. if (mesh instanceof BABYLON.Mesh) {
  75980. mesh.computeWorldMatrix(true);
  75981. matrix = mesh.getWorldMatrix();
  75982. meshPosition = mesh.position.clone();
  75983. meshRotation = mesh.rotation.clone();
  75984. if (mesh.rotationQuaternion) {
  75985. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  75986. }
  75987. meshScaling = mesh.scaling.clone();
  75988. }
  75989. else {
  75990. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  75991. }
  75992. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  75993. var subMeshes = mesh.subMeshes;
  75994. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  75995. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  75996. vertices = [];
  75997. for (var j = 0; j < 3; j++) {
  75998. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  75999. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  76000. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  76001. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  76002. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  76003. vertex = new Vertex(position, normal, uv);
  76004. vertices.push(vertex);
  76005. }
  76006. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  76007. // To handle the case of degenerated triangle
  76008. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  76009. if (polygon.plane)
  76010. polygons.push(polygon);
  76011. }
  76012. }
  76013. var csg = CSG.FromPolygons(polygons);
  76014. csg.matrix = matrix;
  76015. csg.position = meshPosition;
  76016. csg.rotation = meshRotation;
  76017. csg.scaling = meshScaling;
  76018. csg.rotationQuaternion = meshRotationQuaternion;
  76019. currentCSGMeshId++;
  76020. return csg;
  76021. };
  76022. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  76023. CSG.FromPolygons = function (polygons) {
  76024. var csg = new CSG();
  76025. csg.polygons = polygons;
  76026. return csg;
  76027. };
  76028. CSG.prototype.clone = function () {
  76029. var csg = new CSG();
  76030. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  76031. csg.copyTransformAttributes(this);
  76032. return csg;
  76033. };
  76034. CSG.prototype.union = function (csg) {
  76035. var a = new Node(this.clone().polygons);
  76036. var b = new Node(csg.clone().polygons);
  76037. a.clipTo(b);
  76038. b.clipTo(a);
  76039. b.invert();
  76040. b.clipTo(a);
  76041. b.invert();
  76042. a.build(b.allPolygons());
  76043. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76044. };
  76045. CSG.prototype.unionInPlace = function (csg) {
  76046. var a = new Node(this.polygons);
  76047. var b = new Node(csg.polygons);
  76048. a.clipTo(b);
  76049. b.clipTo(a);
  76050. b.invert();
  76051. b.clipTo(a);
  76052. b.invert();
  76053. a.build(b.allPolygons());
  76054. this.polygons = a.allPolygons();
  76055. };
  76056. CSG.prototype.subtract = function (csg) {
  76057. var a = new Node(this.clone().polygons);
  76058. var b = new Node(csg.clone().polygons);
  76059. a.invert();
  76060. a.clipTo(b);
  76061. b.clipTo(a);
  76062. b.invert();
  76063. b.clipTo(a);
  76064. b.invert();
  76065. a.build(b.allPolygons());
  76066. a.invert();
  76067. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76068. };
  76069. CSG.prototype.subtractInPlace = function (csg) {
  76070. var a = new Node(this.polygons);
  76071. var b = new Node(csg.polygons);
  76072. a.invert();
  76073. a.clipTo(b);
  76074. b.clipTo(a);
  76075. b.invert();
  76076. b.clipTo(a);
  76077. b.invert();
  76078. a.build(b.allPolygons());
  76079. a.invert();
  76080. this.polygons = a.allPolygons();
  76081. };
  76082. CSG.prototype.intersect = function (csg) {
  76083. var a = new Node(this.clone().polygons);
  76084. var b = new Node(csg.clone().polygons);
  76085. a.invert();
  76086. b.clipTo(a);
  76087. b.invert();
  76088. a.clipTo(b);
  76089. b.clipTo(a);
  76090. a.build(b.allPolygons());
  76091. a.invert();
  76092. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76093. };
  76094. CSG.prototype.intersectInPlace = function (csg) {
  76095. var a = new Node(this.polygons);
  76096. var b = new Node(csg.polygons);
  76097. a.invert();
  76098. b.clipTo(a);
  76099. b.invert();
  76100. a.clipTo(b);
  76101. b.clipTo(a);
  76102. a.build(b.allPolygons());
  76103. a.invert();
  76104. this.polygons = a.allPolygons();
  76105. };
  76106. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  76107. // not modified.
  76108. CSG.prototype.inverse = function () {
  76109. var csg = this.clone();
  76110. csg.inverseInPlace();
  76111. return csg;
  76112. };
  76113. CSG.prototype.inverseInPlace = function () {
  76114. this.polygons.map(function (p) { p.flip(); });
  76115. };
  76116. // This is used to keep meshes transformations so they can be restored
  76117. // when we build back a Babylon Mesh
  76118. // NB : All CSG operations are performed in world coordinates
  76119. CSG.prototype.copyTransformAttributes = function (csg) {
  76120. this.matrix = csg.matrix;
  76121. this.position = csg.position;
  76122. this.rotation = csg.rotation;
  76123. this.scaling = csg.scaling;
  76124. this.rotationQuaternion = csg.rotationQuaternion;
  76125. return this;
  76126. };
  76127. // Build Raw mesh from CSG
  76128. // Coordinates here are in world space
  76129. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  76130. var matrix = this.matrix.clone();
  76131. matrix.invert();
  76132. 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;
  76133. if (keepSubMeshes) {
  76134. // Sort Polygons, since subMeshes are indices range
  76135. polygons.sort(function (a, b) {
  76136. if (a.shared.meshId === b.shared.meshId) {
  76137. return a.shared.subMeshId - b.shared.subMeshId;
  76138. }
  76139. else {
  76140. return a.shared.meshId - b.shared.meshId;
  76141. }
  76142. });
  76143. }
  76144. for (var i = 0, il = polygons.length; i < il; i++) {
  76145. polygon = polygons[i];
  76146. // Building SubMeshes
  76147. if (!subMesh_dict[polygon.shared.meshId]) {
  76148. subMesh_dict[polygon.shared.meshId] = {};
  76149. }
  76150. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  76151. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  76152. indexStart: +Infinity,
  76153. indexEnd: -Infinity,
  76154. materialIndex: polygon.shared.materialIndex
  76155. };
  76156. }
  76157. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  76158. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  76159. polygonIndices[0] = 0;
  76160. polygonIndices[1] = j - 1;
  76161. polygonIndices[2] = j;
  76162. for (var k = 0; k < 3; k++) {
  76163. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  76164. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  76165. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  76166. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  76167. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  76168. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  76169. // Check if 2 points can be merged
  76170. if (!(typeof vertex_idx !== 'undefined' &&
  76171. normals[vertex_idx * 3] === localNormal.x &&
  76172. normals[vertex_idx * 3 + 1] === localNormal.y &&
  76173. normals[vertex_idx * 3 + 2] === localNormal.z &&
  76174. uvs[vertex_idx * 2] === uv.x &&
  76175. uvs[vertex_idx * 2 + 1] === uv.y)) {
  76176. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  76177. uvs.push(uv.x, uv.y);
  76178. normals.push(normal.x, normal.y, normal.z);
  76179. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  76180. }
  76181. indices.push(vertex_idx);
  76182. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  76183. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  76184. currentIndex++;
  76185. }
  76186. }
  76187. }
  76188. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  76189. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  76190. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  76191. mesh.setIndices(indices, null);
  76192. if (keepSubMeshes) {
  76193. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  76194. var materialIndexOffset = 0, materialMaxIndex;
  76195. mesh.subMeshes = new Array();
  76196. for (var m in subMesh_dict) {
  76197. materialMaxIndex = -1;
  76198. for (var sm in subMesh_dict[m]) {
  76199. subMesh_obj = subMesh_dict[m][sm];
  76200. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  76201. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  76202. }
  76203. materialIndexOffset += ++materialMaxIndex;
  76204. }
  76205. }
  76206. return mesh;
  76207. };
  76208. // Build Mesh from CSG taking material and transforms into account
  76209. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  76210. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  76211. mesh.material = material;
  76212. mesh.position.copyFrom(this.position);
  76213. mesh.rotation.copyFrom(this.rotation);
  76214. if (this.rotationQuaternion) {
  76215. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  76216. }
  76217. mesh.scaling.copyFrom(this.scaling);
  76218. mesh.computeWorldMatrix(true);
  76219. return mesh;
  76220. };
  76221. return CSG;
  76222. }());
  76223. BABYLON.CSG = CSG;
  76224. })(BABYLON || (BABYLON = {}));
  76225. //# sourceMappingURL=babylon.csg.js.map
  76226. var BABYLON;
  76227. (function (BABYLON) {
  76228. var LensFlare = /** @class */ (function () {
  76229. function LensFlare(size, position, color, imgUrl, system) {
  76230. this.size = size;
  76231. this.position = position;
  76232. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  76233. this.color = color || new BABYLON.Color3(1, 1, 1);
  76234. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  76235. this._system = system;
  76236. system.lensFlares.push(this);
  76237. }
  76238. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  76239. return new LensFlare(size, position, color, imgUrl, system);
  76240. };
  76241. LensFlare.prototype.dispose = function () {
  76242. if (this.texture) {
  76243. this.texture.dispose();
  76244. }
  76245. // Remove from scene
  76246. var index = this._system.lensFlares.indexOf(this);
  76247. this._system.lensFlares.splice(index, 1);
  76248. };
  76249. ;
  76250. return LensFlare;
  76251. }());
  76252. BABYLON.LensFlare = LensFlare;
  76253. })(BABYLON || (BABYLON = {}));
  76254. //# sourceMappingURL=babylon.lensFlare.js.map
  76255. var BABYLON;
  76256. (function (BABYLON) {
  76257. var LensFlareSystem = /** @class */ (function () {
  76258. function LensFlareSystem(name, emitter, scene) {
  76259. this.name = name;
  76260. this.lensFlares = new Array();
  76261. this.borderLimit = 300;
  76262. this.viewportBorder = 0;
  76263. this.layerMask = 0x0FFFFFFF;
  76264. this._vertexBuffers = {};
  76265. this._isEnabled = true;
  76266. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76267. this._emitter = emitter;
  76268. this.id = name;
  76269. scene.lensFlareSystems.push(this);
  76270. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  76271. var engine = scene.getEngine();
  76272. // VBO
  76273. var vertices = [];
  76274. vertices.push(1, 1);
  76275. vertices.push(-1, 1);
  76276. vertices.push(-1, -1);
  76277. vertices.push(1, -1);
  76278. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  76279. // Indices
  76280. var indices = [];
  76281. indices.push(0);
  76282. indices.push(1);
  76283. indices.push(2);
  76284. indices.push(0);
  76285. indices.push(2);
  76286. indices.push(3);
  76287. this._indexBuffer = engine.createIndexBuffer(indices);
  76288. // Effects
  76289. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  76290. }
  76291. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  76292. get: function () {
  76293. return this._isEnabled;
  76294. },
  76295. set: function (value) {
  76296. this._isEnabled = value;
  76297. },
  76298. enumerable: true,
  76299. configurable: true
  76300. });
  76301. LensFlareSystem.prototype.getScene = function () {
  76302. return this._scene;
  76303. };
  76304. LensFlareSystem.prototype.getEmitter = function () {
  76305. return this._emitter;
  76306. };
  76307. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  76308. this._emitter = newEmitter;
  76309. };
  76310. LensFlareSystem.prototype.getEmitterPosition = function () {
  76311. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  76312. };
  76313. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  76314. var position = this.getEmitterPosition();
  76315. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  76316. this._positionX = position.x;
  76317. this._positionY = position.y;
  76318. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  76319. if (this.viewportBorder > 0) {
  76320. globalViewport.x -= this.viewportBorder;
  76321. globalViewport.y -= this.viewportBorder;
  76322. globalViewport.width += this.viewportBorder * 2;
  76323. globalViewport.height += this.viewportBorder * 2;
  76324. position.x += this.viewportBorder;
  76325. position.y += this.viewportBorder;
  76326. this._positionX += this.viewportBorder;
  76327. this._positionY += this.viewportBorder;
  76328. }
  76329. if (position.z > 0) {
  76330. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  76331. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  76332. return true;
  76333. }
  76334. return true;
  76335. }
  76336. return false;
  76337. };
  76338. LensFlareSystem.prototype._isVisible = function () {
  76339. if (!this._isEnabled || !this._scene.activeCamera) {
  76340. return false;
  76341. }
  76342. var emitterPosition = this.getEmitterPosition();
  76343. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  76344. var distance = direction.length();
  76345. direction.normalize();
  76346. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  76347. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  76348. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  76349. };
  76350. LensFlareSystem.prototype.render = function () {
  76351. if (!this._effect.isReady() || !this._scene.activeCamera)
  76352. return false;
  76353. var engine = this._scene.getEngine();
  76354. var viewport = this._scene.activeCamera.viewport;
  76355. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  76356. // Position
  76357. if (!this.computeEffectivePosition(globalViewport)) {
  76358. return false;
  76359. }
  76360. // Visibility
  76361. if (!this._isVisible()) {
  76362. return false;
  76363. }
  76364. // Intensity
  76365. var awayX;
  76366. var awayY;
  76367. if (this._positionX < this.borderLimit + globalViewport.x) {
  76368. awayX = this.borderLimit + globalViewport.x - this._positionX;
  76369. }
  76370. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  76371. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  76372. }
  76373. else {
  76374. awayX = 0;
  76375. }
  76376. if (this._positionY < this.borderLimit + globalViewport.y) {
  76377. awayY = this.borderLimit + globalViewport.y - this._positionY;
  76378. }
  76379. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  76380. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  76381. }
  76382. else {
  76383. awayY = 0;
  76384. }
  76385. var away = (awayX > awayY) ? awayX : awayY;
  76386. away -= this.viewportBorder;
  76387. if (away > this.borderLimit) {
  76388. away = this.borderLimit;
  76389. }
  76390. var intensity = 1.0 - (away / this.borderLimit);
  76391. if (intensity < 0) {
  76392. return false;
  76393. }
  76394. if (intensity > 1.0) {
  76395. intensity = 1.0;
  76396. }
  76397. if (this.viewportBorder > 0) {
  76398. globalViewport.x += this.viewportBorder;
  76399. globalViewport.y += this.viewportBorder;
  76400. globalViewport.width -= this.viewportBorder * 2;
  76401. globalViewport.height -= this.viewportBorder * 2;
  76402. this._positionX -= this.viewportBorder;
  76403. this._positionY -= this.viewportBorder;
  76404. }
  76405. // Position
  76406. var centerX = globalViewport.x + globalViewport.width / 2;
  76407. var centerY = globalViewport.y + globalViewport.height / 2;
  76408. var distX = centerX - this._positionX;
  76409. var distY = centerY - this._positionY;
  76410. // Effects
  76411. engine.enableEffect(this._effect);
  76412. engine.setState(false);
  76413. engine.setDepthBuffer(false);
  76414. // VBOs
  76415. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  76416. // Flares
  76417. for (var index = 0; index < this.lensFlares.length; index++) {
  76418. var flare = this.lensFlares[index];
  76419. engine.setAlphaMode(flare.alphaMode);
  76420. var x = centerX - (distX * flare.position);
  76421. var y = centerY - (distY * flare.position);
  76422. var cw = flare.size;
  76423. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  76424. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  76425. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  76426. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  76427. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  76428. // Texture
  76429. this._effect.setTexture("textureSampler", flare.texture);
  76430. // Color
  76431. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  76432. // Draw order
  76433. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76434. }
  76435. engine.setDepthBuffer(true);
  76436. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  76437. return true;
  76438. };
  76439. LensFlareSystem.prototype.dispose = function () {
  76440. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76441. if (vertexBuffer) {
  76442. vertexBuffer.dispose();
  76443. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  76444. }
  76445. if (this._indexBuffer) {
  76446. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  76447. this._indexBuffer = null;
  76448. }
  76449. while (this.lensFlares.length) {
  76450. this.lensFlares[0].dispose();
  76451. }
  76452. // Remove from scene
  76453. var index = this._scene.lensFlareSystems.indexOf(this);
  76454. this._scene.lensFlareSystems.splice(index, 1);
  76455. };
  76456. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  76457. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  76458. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  76459. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  76460. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  76461. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  76462. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  76463. var parsedFlare = parsedLensFlareSystem.flares[index];
  76464. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  76465. }
  76466. return lensFlareSystem;
  76467. };
  76468. LensFlareSystem.prototype.serialize = function () {
  76469. var serializationObject = {};
  76470. serializationObject.id = this.id;
  76471. serializationObject.name = this.name;
  76472. serializationObject.emitterId = this.getEmitter().id;
  76473. serializationObject.borderLimit = this.borderLimit;
  76474. serializationObject.flares = [];
  76475. for (var index = 0; index < this.lensFlares.length; index++) {
  76476. var flare = this.lensFlares[index];
  76477. serializationObject.flares.push({
  76478. size: flare.size,
  76479. position: flare.position,
  76480. color: flare.color.asArray(),
  76481. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  76482. });
  76483. }
  76484. return serializationObject;
  76485. };
  76486. return LensFlareSystem;
  76487. }());
  76488. BABYLON.LensFlareSystem = LensFlareSystem;
  76489. })(BABYLON || (BABYLON = {}));
  76490. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  76491. var BABYLON;
  76492. (function (BABYLON) {
  76493. /**
  76494. * This is a holder class for the physics joint created by the physics plugin.
  76495. * It holds a set of functions to control the underlying joint.
  76496. */
  76497. var PhysicsJoint = /** @class */ (function () {
  76498. function PhysicsJoint(type, jointData) {
  76499. this.type = type;
  76500. this.jointData = jointData;
  76501. jointData.nativeParams = jointData.nativeParams || {};
  76502. }
  76503. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  76504. get: function () {
  76505. return this._physicsJoint;
  76506. },
  76507. set: function (newJoint) {
  76508. if (this._physicsJoint) {
  76509. //remove from the wolrd
  76510. }
  76511. this._physicsJoint = newJoint;
  76512. },
  76513. enumerable: true,
  76514. configurable: true
  76515. });
  76516. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  76517. set: function (physicsPlugin) {
  76518. this._physicsPlugin = physicsPlugin;
  76519. },
  76520. enumerable: true,
  76521. configurable: true
  76522. });
  76523. /**
  76524. * Execute a function that is physics-plugin specific.
  76525. * @param {Function} func the function that will be executed.
  76526. * It accepts two parameters: the physics world and the physics joint.
  76527. */
  76528. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  76529. func(this._physicsPlugin.world, this._physicsJoint);
  76530. };
  76531. //TODO check if the native joints are the same
  76532. //Joint Types
  76533. PhysicsJoint.DistanceJoint = 0;
  76534. PhysicsJoint.HingeJoint = 1;
  76535. PhysicsJoint.BallAndSocketJoint = 2;
  76536. PhysicsJoint.WheelJoint = 3;
  76537. PhysicsJoint.SliderJoint = 4;
  76538. //OIMO
  76539. PhysicsJoint.PrismaticJoint = 5;
  76540. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  76541. PhysicsJoint.UniversalJoint = 6;
  76542. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  76543. //Cannon
  76544. //Similar to a Ball-Joint. Different in params
  76545. PhysicsJoint.PointToPointJoint = 8;
  76546. //Cannon only at the moment
  76547. PhysicsJoint.SpringJoint = 9;
  76548. PhysicsJoint.LockJoint = 10;
  76549. return PhysicsJoint;
  76550. }());
  76551. BABYLON.PhysicsJoint = PhysicsJoint;
  76552. /**
  76553. * A class representing a physics distance joint.
  76554. */
  76555. var DistanceJoint = /** @class */ (function (_super) {
  76556. __extends(DistanceJoint, _super);
  76557. function DistanceJoint(jointData) {
  76558. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  76559. }
  76560. /**
  76561. * Update the predefined distance.
  76562. */
  76563. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  76564. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  76565. };
  76566. return DistanceJoint;
  76567. }(PhysicsJoint));
  76568. BABYLON.DistanceJoint = DistanceJoint;
  76569. var MotorEnabledJoint = /** @class */ (function (_super) {
  76570. __extends(MotorEnabledJoint, _super);
  76571. function MotorEnabledJoint(type, jointData) {
  76572. return _super.call(this, type, jointData) || this;
  76573. }
  76574. /**
  76575. * Set the motor values.
  76576. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76577. * @param {number} force the force to apply
  76578. * @param {number} maxForce max force for this motor.
  76579. */
  76580. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  76581. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  76582. };
  76583. /**
  76584. * Set the motor's limits.
  76585. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76586. */
  76587. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  76588. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  76589. };
  76590. return MotorEnabledJoint;
  76591. }(PhysicsJoint));
  76592. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  76593. /**
  76594. * This class represents a single hinge physics joint
  76595. */
  76596. var HingeJoint = /** @class */ (function (_super) {
  76597. __extends(HingeJoint, _super);
  76598. function HingeJoint(jointData) {
  76599. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  76600. }
  76601. /**
  76602. * Set the motor values.
  76603. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76604. * @param {number} force the force to apply
  76605. * @param {number} maxForce max force for this motor.
  76606. */
  76607. HingeJoint.prototype.setMotor = function (force, maxForce) {
  76608. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  76609. };
  76610. /**
  76611. * Set the motor's limits.
  76612. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76613. */
  76614. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  76615. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  76616. };
  76617. return HingeJoint;
  76618. }(MotorEnabledJoint));
  76619. BABYLON.HingeJoint = HingeJoint;
  76620. /**
  76621. * This class represents a dual hinge physics joint (same as wheel joint)
  76622. */
  76623. var Hinge2Joint = /** @class */ (function (_super) {
  76624. __extends(Hinge2Joint, _super);
  76625. function Hinge2Joint(jointData) {
  76626. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  76627. }
  76628. /**
  76629. * Set the motor values.
  76630. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76631. * @param {number} force the force to apply
  76632. * @param {number} maxForce max force for this motor.
  76633. * @param {motorIndex} the motor's index, 0 or 1.
  76634. */
  76635. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  76636. if (motorIndex === void 0) { motorIndex = 0; }
  76637. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  76638. };
  76639. /**
  76640. * Set the motor limits.
  76641. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76642. * @param {number} upperLimit the upper limit
  76643. * @param {number} lowerLimit lower limit
  76644. * @param {motorIndex} the motor's index, 0 or 1.
  76645. */
  76646. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  76647. if (motorIndex === void 0) { motorIndex = 0; }
  76648. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  76649. };
  76650. return Hinge2Joint;
  76651. }(MotorEnabledJoint));
  76652. BABYLON.Hinge2Joint = Hinge2Joint;
  76653. })(BABYLON || (BABYLON = {}));
  76654. //# sourceMappingURL=babylon.physicsJoint.js.map
  76655. var BABYLON;
  76656. (function (BABYLON) {
  76657. var PhysicsImpostor = /** @class */ (function () {
  76658. function PhysicsImpostor(object, type, _options, _scene) {
  76659. if (_options === void 0) { _options = { mass: 0 }; }
  76660. var _this = this;
  76661. this.object = object;
  76662. this.type = type;
  76663. this._options = _options;
  76664. this._scene = _scene;
  76665. this._bodyUpdateRequired = false;
  76666. this._onBeforePhysicsStepCallbacks = new Array();
  76667. this._onAfterPhysicsStepCallbacks = new Array();
  76668. this._onPhysicsCollideCallbacks = [];
  76669. this._deltaPosition = BABYLON.Vector3.Zero();
  76670. this._isDisposed = false;
  76671. //temp variables for parent rotation calculations
  76672. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  76673. this._tmpQuat = new BABYLON.Quaternion();
  76674. this._tmpQuat2 = new BABYLON.Quaternion();
  76675. /**
  76676. * this function is executed by the physics engine.
  76677. */
  76678. this.beforeStep = function () {
  76679. if (!_this._physicsEngine) {
  76680. return;
  76681. }
  76682. _this.object.translate(_this._deltaPosition, -1);
  76683. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  76684. _this.object.computeWorldMatrix(false);
  76685. if (_this.object.parent && _this.object.rotationQuaternion) {
  76686. _this.getParentsRotation();
  76687. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  76688. }
  76689. else {
  76690. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  76691. }
  76692. if (!_this._options.disableBidirectionalTransformation) {
  76693. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  76694. }
  76695. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  76696. func(_this);
  76697. });
  76698. };
  76699. /**
  76700. * this function is executed by the physics engine.
  76701. */
  76702. this.afterStep = function () {
  76703. if (!_this._physicsEngine) {
  76704. return;
  76705. }
  76706. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  76707. func(_this);
  76708. });
  76709. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  76710. // object has now its world rotation. needs to be converted to local.
  76711. if (_this.object.parent && _this.object.rotationQuaternion) {
  76712. _this.getParentsRotation();
  76713. _this._tmpQuat.conjugateInPlace();
  76714. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  76715. }
  76716. // take the position set and make it the absolute position of this object.
  76717. _this.object.setAbsolutePosition(_this.object.position);
  76718. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  76719. _this.object.translate(_this._deltaPosition, 1);
  76720. };
  76721. /**
  76722. * Legacy collision detection event support
  76723. */
  76724. this.onCollideEvent = null;
  76725. //event and body object due to cannon's event-based architecture.
  76726. this.onCollide = function (e) {
  76727. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  76728. return;
  76729. }
  76730. if (!_this._physicsEngine) {
  76731. return;
  76732. }
  76733. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  76734. if (otherImpostor) {
  76735. // Legacy collision detection event support
  76736. if (_this.onCollideEvent) {
  76737. _this.onCollideEvent(_this, otherImpostor);
  76738. }
  76739. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  76740. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  76741. }).forEach(function (obj) {
  76742. obj.callback(_this, otherImpostor);
  76743. });
  76744. }
  76745. };
  76746. //sanity check!
  76747. if (!this.object) {
  76748. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  76749. return;
  76750. }
  76751. //legacy support for old syntax.
  76752. if (!this._scene && object.getScene) {
  76753. this._scene = object.getScene();
  76754. }
  76755. if (!this._scene) {
  76756. return;
  76757. }
  76758. this._physicsEngine = this._scene.getPhysicsEngine();
  76759. if (!this._physicsEngine) {
  76760. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  76761. }
  76762. else {
  76763. //set the object's quaternion, if not set
  76764. if (!this.object.rotationQuaternion) {
  76765. if (this.object.rotation) {
  76766. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  76767. }
  76768. else {
  76769. this.object.rotationQuaternion = new BABYLON.Quaternion();
  76770. }
  76771. }
  76772. //default options params
  76773. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  76774. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  76775. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  76776. this._joints = [];
  76777. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  76778. if (!this.object.parent || this._options.ignoreParent) {
  76779. this._init();
  76780. }
  76781. else if (this.object.parent.physicsImpostor) {
  76782. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  76783. }
  76784. }
  76785. }
  76786. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  76787. get: function () {
  76788. return this._isDisposed;
  76789. },
  76790. enumerable: true,
  76791. configurable: true
  76792. });
  76793. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  76794. get: function () {
  76795. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  76796. },
  76797. set: function (value) {
  76798. this.setMass(value);
  76799. },
  76800. enumerable: true,
  76801. configurable: true
  76802. });
  76803. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  76804. get: function () {
  76805. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  76806. },
  76807. set: function (value) {
  76808. if (!this._physicsEngine) {
  76809. return;
  76810. }
  76811. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  76812. },
  76813. enumerable: true,
  76814. configurable: true
  76815. });
  76816. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  76817. get: function () {
  76818. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  76819. },
  76820. set: function (value) {
  76821. if (!this._physicsEngine) {
  76822. return;
  76823. }
  76824. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  76825. },
  76826. enumerable: true,
  76827. configurable: true
  76828. });
  76829. /**
  76830. * This function will completly initialize this impostor.
  76831. * It will create a new body - but only if this mesh has no parent.
  76832. * If it has, this impostor will not be used other than to define the impostor
  76833. * of the child mesh.
  76834. */
  76835. PhysicsImpostor.prototype._init = function () {
  76836. if (!this._physicsEngine) {
  76837. return;
  76838. }
  76839. this._physicsEngine.removeImpostor(this);
  76840. this.physicsBody = null;
  76841. this._parent = this._parent || this._getPhysicsParent();
  76842. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  76843. this._physicsEngine.addImpostor(this);
  76844. }
  76845. };
  76846. PhysicsImpostor.prototype._getPhysicsParent = function () {
  76847. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  76848. var parentMesh = this.object.parent;
  76849. return parentMesh.physicsImpostor;
  76850. }
  76851. return null;
  76852. };
  76853. /**
  76854. * Should a new body be generated.
  76855. */
  76856. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  76857. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  76858. };
  76859. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  76860. this.forceUpdate();
  76861. };
  76862. /**
  76863. * Force a regeneration of this or the parent's impostor's body.
  76864. * Use under cautious - This will remove all joints already implemented.
  76865. */
  76866. PhysicsImpostor.prototype.forceUpdate = function () {
  76867. this._init();
  76868. if (this.parent && !this._options.ignoreParent) {
  76869. this.parent.forceUpdate();
  76870. }
  76871. };
  76872. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  76873. /*public get mesh(): AbstractMesh {
  76874. return this._mesh;
  76875. }*/
  76876. /**
  76877. * Gets the body that holds this impostor. Either its own, or its parent.
  76878. */
  76879. get: function () {
  76880. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  76881. },
  76882. /**
  76883. * Set the physics body. Used mainly by the physics engine/plugin
  76884. */
  76885. set: function (physicsBody) {
  76886. if (this._physicsBody && this._physicsEngine) {
  76887. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  76888. }
  76889. this._physicsBody = physicsBody;
  76890. this.resetUpdateFlags();
  76891. },
  76892. enumerable: true,
  76893. configurable: true
  76894. });
  76895. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  76896. get: function () {
  76897. return !this._options.ignoreParent && this._parent ? this._parent : null;
  76898. },
  76899. set: function (value) {
  76900. this._parent = value;
  76901. },
  76902. enumerable: true,
  76903. configurable: true
  76904. });
  76905. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  76906. this._bodyUpdateRequired = false;
  76907. };
  76908. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  76909. if (this.object.getBoundingInfo) {
  76910. var q = this.object.rotationQuaternion;
  76911. //reset rotation
  76912. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  76913. //calculate the world matrix with no rotation
  76914. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  76915. var boundingInfo = this.object.getBoundingInfo();
  76916. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  76917. //bring back the rotation
  76918. this.object.rotationQuaternion = q;
  76919. //calculate the world matrix with the new rotation
  76920. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  76921. return size;
  76922. }
  76923. else {
  76924. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  76925. }
  76926. };
  76927. PhysicsImpostor.prototype.getObjectCenter = function () {
  76928. if (this.object.getBoundingInfo) {
  76929. var boundingInfo = this.object.getBoundingInfo();
  76930. return boundingInfo.boundingBox.centerWorld;
  76931. }
  76932. else {
  76933. return this.object.position;
  76934. }
  76935. };
  76936. /**
  76937. * Get a specific parametes from the options parameter.
  76938. */
  76939. PhysicsImpostor.prototype.getParam = function (paramName) {
  76940. return this._options[paramName];
  76941. };
  76942. /**
  76943. * Sets a specific parameter in the options given to the physics plugin
  76944. */
  76945. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  76946. this._options[paramName] = value;
  76947. this._bodyUpdateRequired = true;
  76948. };
  76949. /**
  76950. * Specifically change the body's mass option. Won't recreate the physics body object
  76951. */
  76952. PhysicsImpostor.prototype.setMass = function (mass) {
  76953. if (this.getParam("mass") !== mass) {
  76954. this.setParam("mass", mass);
  76955. }
  76956. if (this._physicsEngine) {
  76957. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  76958. }
  76959. };
  76960. PhysicsImpostor.prototype.getLinearVelocity = function () {
  76961. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  76962. };
  76963. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  76964. if (this._physicsEngine) {
  76965. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  76966. }
  76967. };
  76968. PhysicsImpostor.prototype.getAngularVelocity = function () {
  76969. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  76970. };
  76971. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  76972. if (this._physicsEngine) {
  76973. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  76974. }
  76975. };
  76976. /**
  76977. * Execute a function with the physics plugin native code.
  76978. * Provide a function the will have two variables - the world object and the physics body object.
  76979. */
  76980. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  76981. if (this._physicsEngine) {
  76982. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  76983. }
  76984. };
  76985. /**
  76986. * Register a function that will be executed before the physics world is stepping forward.
  76987. */
  76988. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  76989. this._onBeforePhysicsStepCallbacks.push(func);
  76990. };
  76991. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  76992. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  76993. if (index > -1) {
  76994. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  76995. }
  76996. else {
  76997. BABYLON.Tools.Warn("Function to remove was not found");
  76998. }
  76999. };
  77000. /**
  77001. * Register a function that will be executed after the physics step
  77002. */
  77003. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  77004. this._onAfterPhysicsStepCallbacks.push(func);
  77005. };
  77006. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  77007. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  77008. if (index > -1) {
  77009. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  77010. }
  77011. else {
  77012. BABYLON.Tools.Warn("Function to remove was not found");
  77013. }
  77014. };
  77015. /**
  77016. * register a function that will be executed when this impostor collides against a different body.
  77017. */
  77018. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  77019. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  77020. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  77021. };
  77022. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  77023. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  77024. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  77025. if (index > -1) {
  77026. this._onPhysicsCollideCallbacks.splice(index, 1);
  77027. }
  77028. else {
  77029. BABYLON.Tools.Warn("Function to remove was not found");
  77030. }
  77031. };
  77032. PhysicsImpostor.prototype.getParentsRotation = function () {
  77033. var parent = this.object.parent;
  77034. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  77035. while (parent) {
  77036. if (parent.rotationQuaternion) {
  77037. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  77038. }
  77039. else {
  77040. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  77041. }
  77042. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  77043. parent = parent.parent;
  77044. }
  77045. return this._tmpQuat;
  77046. };
  77047. /**
  77048. * Apply a force
  77049. */
  77050. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  77051. if (this._physicsEngine) {
  77052. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  77053. }
  77054. return this;
  77055. };
  77056. /**
  77057. * Apply an impulse
  77058. */
  77059. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  77060. if (this._physicsEngine) {
  77061. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  77062. }
  77063. return this;
  77064. };
  77065. /**
  77066. * A help function to create a joint.
  77067. */
  77068. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  77069. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  77070. this.addJoint(otherImpostor, joint);
  77071. return this;
  77072. };
  77073. /**
  77074. * Add a joint to this impostor with a different impostor.
  77075. */
  77076. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  77077. this._joints.push({
  77078. otherImpostor: otherImpostor,
  77079. joint: joint
  77080. });
  77081. if (this._physicsEngine) {
  77082. this._physicsEngine.addJoint(this, otherImpostor, joint);
  77083. }
  77084. return this;
  77085. };
  77086. /**
  77087. * Will keep this body still, in a sleep mode.
  77088. */
  77089. PhysicsImpostor.prototype.sleep = function () {
  77090. if (this._physicsEngine) {
  77091. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  77092. }
  77093. return this;
  77094. };
  77095. /**
  77096. * Wake the body up.
  77097. */
  77098. PhysicsImpostor.prototype.wakeUp = function () {
  77099. if (this._physicsEngine) {
  77100. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  77101. }
  77102. return this;
  77103. };
  77104. PhysicsImpostor.prototype.clone = function (newObject) {
  77105. if (!newObject)
  77106. return null;
  77107. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  77108. };
  77109. PhysicsImpostor.prototype.dispose = function () {
  77110. var _this = this;
  77111. //no dispose if no physics engine is available.
  77112. if (!this._physicsEngine) {
  77113. return;
  77114. }
  77115. this._joints.forEach(function (j) {
  77116. if (_this._physicsEngine) {
  77117. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  77118. }
  77119. });
  77120. //dispose the physics body
  77121. this._physicsEngine.removeImpostor(this);
  77122. if (this.parent) {
  77123. this.parent.forceUpdate();
  77124. }
  77125. else {
  77126. /*this._object.getChildMeshes().forEach(function(mesh) {
  77127. if (mesh.physicsImpostor) {
  77128. if (disposeChildren) {
  77129. mesh.physicsImpostor.dispose();
  77130. mesh.physicsImpostor = null;
  77131. }
  77132. }
  77133. })*/
  77134. }
  77135. this._isDisposed = true;
  77136. };
  77137. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  77138. this._deltaPosition.copyFrom(position);
  77139. };
  77140. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  77141. if (!this._deltaRotation) {
  77142. this._deltaRotation = new BABYLON.Quaternion();
  77143. }
  77144. this._deltaRotation.copyFrom(rotation);
  77145. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  77146. };
  77147. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  77148. if (this._physicsEngine) {
  77149. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  77150. }
  77151. return this;
  77152. };
  77153. PhysicsImpostor.prototype.getRadius = function () {
  77154. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  77155. };
  77156. /**
  77157. * Sync a bone with this impostor
  77158. * @param bone The bone to sync to the impostor.
  77159. * @param boneMesh The mesh that the bone is influencing.
  77160. * @param jointPivot The pivot of the joint / bone in local space.
  77161. * @param distToJoint Optional distance from the impostor to the joint.
  77162. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  77163. */
  77164. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  77165. var tempVec = PhysicsImpostor._tmpVecs[0];
  77166. var mesh = this.object;
  77167. if (mesh.rotationQuaternion) {
  77168. if (adjustRotation) {
  77169. var tempQuat = PhysicsImpostor._tmpQuat;
  77170. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  77171. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  77172. }
  77173. else {
  77174. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  77175. }
  77176. }
  77177. tempVec.x = 0;
  77178. tempVec.y = 0;
  77179. tempVec.z = 0;
  77180. if (jointPivot) {
  77181. tempVec.x = jointPivot.x;
  77182. tempVec.y = jointPivot.y;
  77183. tempVec.z = jointPivot.z;
  77184. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  77185. if (distToJoint === undefined || distToJoint === null) {
  77186. distToJoint = jointPivot.length();
  77187. }
  77188. tempVec.x *= distToJoint;
  77189. tempVec.y *= distToJoint;
  77190. tempVec.z *= distToJoint;
  77191. }
  77192. if (bone.getParent()) {
  77193. tempVec.addInPlace(mesh.getAbsolutePosition());
  77194. bone.setAbsolutePosition(tempVec, boneMesh);
  77195. }
  77196. else {
  77197. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  77198. boneMesh.position.x -= tempVec.x;
  77199. boneMesh.position.y -= tempVec.y;
  77200. boneMesh.position.z -= tempVec.z;
  77201. }
  77202. };
  77203. /**
  77204. * Sync impostor to a bone
  77205. * @param bone The bone that the impostor will be synced to.
  77206. * @param boneMesh The mesh that the bone is influencing.
  77207. * @param jointPivot The pivot of the joint / bone in local space.
  77208. * @param distToJoint Optional distance from the impostor to the joint.
  77209. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  77210. * @param boneAxis Optional vector3 axis the bone is aligned with
  77211. */
  77212. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  77213. var mesh = this.object;
  77214. if (mesh.rotationQuaternion) {
  77215. if (adjustRotation) {
  77216. var tempQuat = PhysicsImpostor._tmpQuat;
  77217. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  77218. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  77219. }
  77220. else {
  77221. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  77222. }
  77223. }
  77224. var pos = PhysicsImpostor._tmpVecs[0];
  77225. var boneDir = PhysicsImpostor._tmpVecs[1];
  77226. if (!boneAxis) {
  77227. boneAxis = PhysicsImpostor._tmpVecs[2];
  77228. boneAxis.x = 0;
  77229. boneAxis.y = 1;
  77230. boneAxis.z = 0;
  77231. }
  77232. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  77233. bone.getAbsolutePositionToRef(boneMesh, pos);
  77234. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  77235. distToJoint = jointPivot.length();
  77236. }
  77237. if (distToJoint !== undefined && distToJoint !== null) {
  77238. pos.x += boneDir.x * distToJoint;
  77239. pos.y += boneDir.y * distToJoint;
  77240. pos.z += boneDir.z * distToJoint;
  77241. }
  77242. mesh.setAbsolutePosition(pos);
  77243. };
  77244. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  77245. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  77246. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77247. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  77248. //Impostor types
  77249. PhysicsImpostor.NoImpostor = 0;
  77250. PhysicsImpostor.SphereImpostor = 1;
  77251. PhysicsImpostor.BoxImpostor = 2;
  77252. PhysicsImpostor.PlaneImpostor = 3;
  77253. PhysicsImpostor.MeshImpostor = 4;
  77254. PhysicsImpostor.CylinderImpostor = 7;
  77255. PhysicsImpostor.ParticleImpostor = 8;
  77256. PhysicsImpostor.HeightmapImpostor = 9;
  77257. return PhysicsImpostor;
  77258. }());
  77259. BABYLON.PhysicsImpostor = PhysicsImpostor;
  77260. })(BABYLON || (BABYLON = {}));
  77261. //# sourceMappingURL=babylon.physicsImpostor.js.map
  77262. var BABYLON;
  77263. (function (BABYLON) {
  77264. var PhysicsEngine = /** @class */ (function () {
  77265. function PhysicsEngine(gravity, _physicsPlugin) {
  77266. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  77267. this._physicsPlugin = _physicsPlugin;
  77268. //new methods and parameters
  77269. this._impostors = [];
  77270. this._joints = [];
  77271. if (!this._physicsPlugin.isSupported()) {
  77272. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  77273. + "Please make sure it is included.");
  77274. }
  77275. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  77276. this.setGravity(gravity);
  77277. this.setTimeStep();
  77278. }
  77279. PhysicsEngine.prototype.setGravity = function (gravity) {
  77280. this.gravity = gravity;
  77281. this._physicsPlugin.setGravity(this.gravity);
  77282. };
  77283. /**
  77284. * Set the time step of the physics engine.
  77285. * default is 1/60.
  77286. * To slow it down, enter 1/600 for example.
  77287. * To speed it up, 1/30
  77288. * @param {number} newTimeStep the new timestep to apply to this world.
  77289. */
  77290. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  77291. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  77292. this._physicsPlugin.setTimeStep(newTimeStep);
  77293. };
  77294. /**
  77295. * Get the time step of the physics engine.
  77296. */
  77297. PhysicsEngine.prototype.getTimeStep = function () {
  77298. return this._physicsPlugin.getTimeStep();
  77299. };
  77300. PhysicsEngine.prototype.dispose = function () {
  77301. this._impostors.forEach(function (impostor) {
  77302. impostor.dispose();
  77303. });
  77304. this._physicsPlugin.dispose();
  77305. };
  77306. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  77307. return this._physicsPlugin.name;
  77308. };
  77309. /**
  77310. * Adding a new impostor for the impostor tracking.
  77311. * This will be done by the impostor itself.
  77312. * @param {PhysicsImpostor} impostor the impostor to add
  77313. */
  77314. PhysicsEngine.prototype.addImpostor = function (impostor) {
  77315. impostor.uniqueId = this._impostors.push(impostor);
  77316. //if no parent, generate the body
  77317. if (!impostor.parent) {
  77318. this._physicsPlugin.generatePhysicsBody(impostor);
  77319. }
  77320. };
  77321. /**
  77322. * Remove an impostor from the engine.
  77323. * This impostor and its mesh will not longer be updated by the physics engine.
  77324. * @param {PhysicsImpostor} impostor the impostor to remove
  77325. */
  77326. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  77327. var index = this._impostors.indexOf(impostor);
  77328. if (index > -1) {
  77329. var removed = this._impostors.splice(index, 1);
  77330. //Is it needed?
  77331. if (removed.length) {
  77332. //this will also remove it from the world.
  77333. removed[0].physicsBody = null;
  77334. }
  77335. }
  77336. };
  77337. /**
  77338. * Add a joint to the physics engine
  77339. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  77340. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  77341. * @param {PhysicsJoint} the joint that will connect both impostors.
  77342. */
  77343. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  77344. var impostorJoint = {
  77345. mainImpostor: mainImpostor,
  77346. connectedImpostor: connectedImpostor,
  77347. joint: joint
  77348. };
  77349. joint.physicsPlugin = this._physicsPlugin;
  77350. this._joints.push(impostorJoint);
  77351. this._physicsPlugin.generateJoint(impostorJoint);
  77352. };
  77353. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  77354. var matchingJoints = this._joints.filter(function (impostorJoint) {
  77355. return (impostorJoint.connectedImpostor === connectedImpostor
  77356. && impostorJoint.joint === joint
  77357. && impostorJoint.mainImpostor === mainImpostor);
  77358. });
  77359. if (matchingJoints.length) {
  77360. this._physicsPlugin.removeJoint(matchingJoints[0]);
  77361. //TODO remove it from the list as well
  77362. }
  77363. };
  77364. /**
  77365. * Called by the scene. no need to call it.
  77366. */
  77367. PhysicsEngine.prototype._step = function (delta) {
  77368. var _this = this;
  77369. //check if any mesh has no body / requires an update
  77370. this._impostors.forEach(function (impostor) {
  77371. if (impostor.isBodyInitRequired()) {
  77372. _this._physicsPlugin.generatePhysicsBody(impostor);
  77373. }
  77374. });
  77375. if (delta > 0.1) {
  77376. delta = 0.1;
  77377. }
  77378. else if (delta <= 0) {
  77379. delta = 1.0 / 60.0;
  77380. }
  77381. this._physicsPlugin.executeStep(delta, this._impostors);
  77382. };
  77383. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  77384. return this._physicsPlugin;
  77385. };
  77386. PhysicsEngine.prototype.getImpostors = function () {
  77387. return this._impostors;
  77388. };
  77389. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  77390. for (var i = 0; i < this._impostors.length; ++i) {
  77391. if (this._impostors[i].object === object) {
  77392. return this._impostors[i];
  77393. }
  77394. }
  77395. return null;
  77396. };
  77397. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  77398. for (var i = 0; i < this._impostors.length; ++i) {
  77399. if (this._impostors[i].physicsBody === body) {
  77400. return this._impostors[i];
  77401. }
  77402. }
  77403. return null;
  77404. };
  77405. // Statics
  77406. PhysicsEngine.Epsilon = 0.001;
  77407. return PhysicsEngine;
  77408. }());
  77409. BABYLON.PhysicsEngine = PhysicsEngine;
  77410. })(BABYLON || (BABYLON = {}));
  77411. //# sourceMappingURL=babylon.physicsEngine.js.map
  77412. var BABYLON;
  77413. (function (BABYLON) {
  77414. var PhysicsHelper = /** @class */ (function () {
  77415. function PhysicsHelper(scene) {
  77416. this._scene = scene;
  77417. this._physicsEngine = this._scene.getPhysicsEngine();
  77418. if (!this._physicsEngine) {
  77419. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  77420. }
  77421. }
  77422. /**
  77423. * @param {Vector3} origin the origin of the explosion
  77424. * @param {number} radius the explosion radius
  77425. * @param {number} strength the explosion strength
  77426. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77427. */
  77428. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  77429. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77430. if (!this._physicsEngine) {
  77431. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  77432. return null;
  77433. }
  77434. var impostors = this._physicsEngine.getImpostors();
  77435. if (impostors.length === 0) {
  77436. return null;
  77437. }
  77438. var event = new PhysicsRadialExplosionEvent(this._scene);
  77439. impostors.forEach(function (impostor) {
  77440. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  77441. if (!impostorForceAndContactPoint) {
  77442. return;
  77443. }
  77444. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77445. });
  77446. event.dispose(false);
  77447. return event;
  77448. };
  77449. /**
  77450. * @param {Vector3} origin the origin of the explosion
  77451. * @param {number} radius the explosion radius
  77452. * @param {number} strength the explosion strength
  77453. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77454. */
  77455. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  77456. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77457. if (!this._physicsEngine) {
  77458. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77459. return null;
  77460. }
  77461. var impostors = this._physicsEngine.getImpostors();
  77462. if (impostors.length === 0) {
  77463. return null;
  77464. }
  77465. var event = new PhysicsRadialExplosionEvent(this._scene);
  77466. impostors.forEach(function (impostor) {
  77467. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  77468. if (!impostorForceAndContactPoint) {
  77469. return;
  77470. }
  77471. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77472. });
  77473. event.dispose(false);
  77474. return event;
  77475. };
  77476. /**
  77477. * @param {Vector3} origin the origin of the explosion
  77478. * @param {number} radius the explosion radius
  77479. * @param {number} strength the explosion strength
  77480. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77481. */
  77482. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  77483. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77484. if (!this._physicsEngine) {
  77485. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77486. return null;
  77487. }
  77488. var impostors = this._physicsEngine.getImpostors();
  77489. if (impostors.length === 0) {
  77490. return null;
  77491. }
  77492. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  77493. event.dispose(false);
  77494. return event;
  77495. };
  77496. /**
  77497. * @param {Vector3} origin the origin of the updraft
  77498. * @param {number} radius the radius of the updraft
  77499. * @param {number} strength the strength of the updraft
  77500. * @param {number} height the height of the updraft
  77501. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  77502. */
  77503. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  77504. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  77505. if (!this._physicsEngine) {
  77506. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77507. return null;
  77508. }
  77509. if (this._physicsEngine.getImpostors().length === 0) {
  77510. return null;
  77511. }
  77512. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  77513. event.dispose(false);
  77514. return event;
  77515. };
  77516. /**
  77517. * @param {Vector3} origin the of the vortex
  77518. * @param {number} radius the radius of the vortex
  77519. * @param {number} strength the strength of the vortex
  77520. * @param {number} height the height of the vortex
  77521. */
  77522. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  77523. if (!this._physicsEngine) {
  77524. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77525. return null;
  77526. }
  77527. if (this._physicsEngine.getImpostors().length === 0) {
  77528. return null;
  77529. }
  77530. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  77531. event.dispose(false);
  77532. return event;
  77533. };
  77534. return PhysicsHelper;
  77535. }());
  77536. BABYLON.PhysicsHelper = PhysicsHelper;
  77537. /***** Radial explosion *****/
  77538. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  77539. function PhysicsRadialExplosionEvent(scene) {
  77540. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  77541. this._rays = [];
  77542. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  77543. this._scene = scene;
  77544. }
  77545. /**
  77546. * Returns the data related to the radial explosion event (sphere & rays).
  77547. * @returns {PhysicsRadialExplosionEventData}
  77548. */
  77549. PhysicsRadialExplosionEvent.prototype.getData = function () {
  77550. this._dataFetched = true;
  77551. return {
  77552. sphere: this._sphere,
  77553. rays: this._rays,
  77554. };
  77555. };
  77556. /**
  77557. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  77558. * @param impostor
  77559. * @param {Vector3} origin the origin of the explosion
  77560. * @param {number} radius the explosion radius
  77561. * @param {number} strength the explosion strength
  77562. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  77563. * @returns {Nullable<PhysicsForceAndContactPoint>}
  77564. */
  77565. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  77566. if (impostor.mass === 0) {
  77567. return null;
  77568. }
  77569. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  77570. return null;
  77571. }
  77572. if (impostor.object.getClassName() !== 'Mesh') {
  77573. return null;
  77574. }
  77575. var impostorObject = impostor.object;
  77576. var impostorObjectCenter = impostor.getObjectCenter();
  77577. var direction = impostorObjectCenter.subtract(origin);
  77578. var ray = new BABYLON.Ray(origin, direction, radius);
  77579. this._rays.push(ray);
  77580. var hit = ray.intersectsMesh(impostorObject);
  77581. var contactPoint = hit.pickedPoint;
  77582. if (!contactPoint) {
  77583. return null;
  77584. }
  77585. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  77586. if (distanceFromOrigin > radius) {
  77587. return null;
  77588. }
  77589. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  77590. ? strength
  77591. : strength * (1 - (distanceFromOrigin / radius));
  77592. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  77593. return { force: force, contactPoint: contactPoint };
  77594. };
  77595. /**
  77596. * Disposes the sphere.
  77597. * @param {bolean} force
  77598. */
  77599. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  77600. var _this = this;
  77601. if (force === void 0) { force = true; }
  77602. if (force) {
  77603. this._sphere.dispose();
  77604. }
  77605. else {
  77606. setTimeout(function () {
  77607. if (!_this._dataFetched) {
  77608. _this._sphere.dispose();
  77609. }
  77610. }, 0);
  77611. }
  77612. };
  77613. /*** Helpers ***/
  77614. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  77615. if (!this._sphere) {
  77616. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  77617. this._sphere.isVisible = false;
  77618. }
  77619. };
  77620. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  77621. var impostorObject = impostor.object;
  77622. this._prepareSphere();
  77623. this._sphere.position = origin;
  77624. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  77625. this._sphere._updateBoundingInfo();
  77626. this._sphere.computeWorldMatrix(true);
  77627. return this._sphere.intersectsMesh(impostorObject, true);
  77628. };
  77629. return PhysicsRadialExplosionEvent;
  77630. }());
  77631. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  77632. /***** Gravitational Field *****/
  77633. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  77634. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  77635. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77636. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  77637. this._physicsHelper = physicsHelper;
  77638. this._scene = scene;
  77639. this._origin = origin;
  77640. this._radius = radius;
  77641. this._strength = strength;
  77642. this._falloff = falloff;
  77643. this._tickCallback = this._tick.bind(this);
  77644. }
  77645. /**
  77646. * Returns the data related to the gravitational field event (sphere).
  77647. * @returns {PhysicsGravitationalFieldEventData}
  77648. */
  77649. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  77650. this._dataFetched = true;
  77651. return {
  77652. sphere: this._sphere,
  77653. };
  77654. };
  77655. /**
  77656. * Enables the gravitational field.
  77657. */
  77658. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  77659. this._tickCallback.call(this);
  77660. this._scene.registerBeforeRender(this._tickCallback);
  77661. };
  77662. /**
  77663. * Disables the gravitational field.
  77664. */
  77665. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  77666. this._scene.unregisterBeforeRender(this._tickCallback);
  77667. };
  77668. /**
  77669. * Disposes the sphere.
  77670. * @param {bolean} force
  77671. */
  77672. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  77673. var _this = this;
  77674. if (force === void 0) { force = true; }
  77675. if (force) {
  77676. this._sphere.dispose();
  77677. }
  77678. else {
  77679. setTimeout(function () {
  77680. if (!_this._dataFetched) {
  77681. _this._sphere.dispose();
  77682. }
  77683. }, 0);
  77684. }
  77685. };
  77686. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  77687. // Since the params won't change, we fetch the event only once
  77688. if (this._sphere) {
  77689. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  77690. }
  77691. else {
  77692. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  77693. if (radialExplosionEvent) {
  77694. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  77695. }
  77696. }
  77697. };
  77698. return PhysicsGravitationalFieldEvent;
  77699. }());
  77700. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  77701. /***** Updraft *****/
  77702. var PhysicsUpdraftEvent = /** @class */ (function () {
  77703. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  77704. this._scene = _scene;
  77705. this._origin = _origin;
  77706. this._radius = _radius;
  77707. this._strength = _strength;
  77708. this._height = _height;
  77709. this._updraftMode = _updraftMode;
  77710. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  77711. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  77712. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  77713. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  77714. this._physicsEngine = this._scene.getPhysicsEngine();
  77715. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  77716. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  77717. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  77718. this._originDirection = this._origin.subtract(this._originTop).normalize();
  77719. }
  77720. this._tickCallback = this._tick.bind(this);
  77721. }
  77722. /**
  77723. * Returns the data related to the updraft event (cylinder).
  77724. * @returns {PhysicsUpdraftEventData}
  77725. */
  77726. PhysicsUpdraftEvent.prototype.getData = function () {
  77727. this._dataFetched = true;
  77728. return {
  77729. cylinder: this._cylinder,
  77730. };
  77731. };
  77732. /**
  77733. * Enables the updraft.
  77734. */
  77735. PhysicsUpdraftEvent.prototype.enable = function () {
  77736. this._tickCallback.call(this);
  77737. this._scene.registerBeforeRender(this._tickCallback);
  77738. };
  77739. /**
  77740. * Disables the cortex.
  77741. */
  77742. PhysicsUpdraftEvent.prototype.disable = function () {
  77743. this._scene.unregisterBeforeRender(this._tickCallback);
  77744. };
  77745. /**
  77746. * Disposes the sphere.
  77747. * @param {bolean} force
  77748. */
  77749. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  77750. var _this = this;
  77751. if (force === void 0) { force = true; }
  77752. if (force) {
  77753. this._cylinder.dispose();
  77754. }
  77755. else {
  77756. setTimeout(function () {
  77757. if (!_this._dataFetched) {
  77758. _this._cylinder.dispose();
  77759. }
  77760. }, 0);
  77761. }
  77762. };
  77763. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  77764. if (impostor.mass === 0) {
  77765. return null;
  77766. }
  77767. if (!this._intersectsWithCylinder(impostor)) {
  77768. return null;
  77769. }
  77770. var impostorObjectCenter = impostor.getObjectCenter();
  77771. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  77772. var direction = this._originDirection;
  77773. }
  77774. else {
  77775. var direction = impostorObjectCenter.subtract(this._originTop);
  77776. }
  77777. var multiplier = this._strength * -1;
  77778. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  77779. return { force: force, contactPoint: impostorObjectCenter };
  77780. };
  77781. PhysicsUpdraftEvent.prototype._tick = function () {
  77782. var _this = this;
  77783. this._physicsEngine.getImpostors().forEach(function (impostor) {
  77784. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  77785. if (!impostorForceAndContactPoint) {
  77786. return;
  77787. }
  77788. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77789. });
  77790. };
  77791. /*** Helpers ***/
  77792. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  77793. if (!this._cylinder) {
  77794. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  77795. height: this._height,
  77796. diameter: this._radius * 2,
  77797. }, this._scene);
  77798. this._cylinder.isVisible = false;
  77799. }
  77800. };
  77801. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  77802. var impostorObject = impostor.object;
  77803. this._prepareCylinder();
  77804. this._cylinder.position = this._cylinderPosition;
  77805. return this._cylinder.intersectsMesh(impostorObject, true);
  77806. };
  77807. return PhysicsUpdraftEvent;
  77808. }());
  77809. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  77810. /***** Vortex *****/
  77811. var PhysicsVortexEvent = /** @class */ (function () {
  77812. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  77813. this._scene = _scene;
  77814. this._origin = _origin;
  77815. this._radius = _radius;
  77816. this._strength = _strength;
  77817. this._height = _height;
  77818. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  77819. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  77820. this._updraftMultiplier = 0.02;
  77821. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  77822. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  77823. this._physicsEngine = this._scene.getPhysicsEngine();
  77824. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  77825. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  77826. this._tickCallback = this._tick.bind(this);
  77827. }
  77828. /**
  77829. * Returns the data related to the vortex event (cylinder).
  77830. * @returns {PhysicsVortexEventData}
  77831. */
  77832. PhysicsVortexEvent.prototype.getData = function () {
  77833. this._dataFetched = true;
  77834. return {
  77835. cylinder: this._cylinder,
  77836. };
  77837. };
  77838. /**
  77839. * Enables the vortex.
  77840. */
  77841. PhysicsVortexEvent.prototype.enable = function () {
  77842. this._tickCallback.call(this);
  77843. this._scene.registerBeforeRender(this._tickCallback);
  77844. };
  77845. /**
  77846. * Disables the cortex.
  77847. */
  77848. PhysicsVortexEvent.prototype.disable = function () {
  77849. this._scene.unregisterBeforeRender(this._tickCallback);
  77850. };
  77851. /**
  77852. * Disposes the sphere.
  77853. * @param {bolean} force
  77854. */
  77855. PhysicsVortexEvent.prototype.dispose = function (force) {
  77856. var _this = this;
  77857. if (force === void 0) { force = true; }
  77858. if (force) {
  77859. this._cylinder.dispose();
  77860. }
  77861. else {
  77862. setTimeout(function () {
  77863. if (!_this._dataFetched) {
  77864. _this._cylinder.dispose();
  77865. }
  77866. }, 0);
  77867. }
  77868. };
  77869. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  77870. if (impostor.mass === 0) {
  77871. return null;
  77872. }
  77873. if (!this._intersectsWithCylinder(impostor)) {
  77874. return null;
  77875. }
  77876. if (impostor.object.getClassName() !== 'Mesh') {
  77877. return null;
  77878. }
  77879. var impostorObject = impostor.object;
  77880. var impostorObjectCenter = impostor.getObjectCenter();
  77881. 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)
  77882. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  77883. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  77884. var hit = ray.intersectsMesh(impostorObject);
  77885. var contactPoint = hit.pickedPoint;
  77886. if (!contactPoint) {
  77887. return null;
  77888. }
  77889. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  77890. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  77891. var directionToOrigin = contactPoint.normalize();
  77892. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  77893. directionToOrigin = directionToOrigin.negate();
  77894. }
  77895. // TODO: find a more physically based solution
  77896. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  77897. var forceX = directionToOrigin.x * this._strength / 8;
  77898. var forceY = directionToOrigin.y * this._updraftMultiplier;
  77899. var forceZ = directionToOrigin.z * this._strength / 8;
  77900. }
  77901. else {
  77902. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  77903. var forceY = this._originTop.y * this._updraftMultiplier;
  77904. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  77905. }
  77906. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  77907. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  77908. return { force: force, contactPoint: impostorObjectCenter };
  77909. };
  77910. PhysicsVortexEvent.prototype._tick = function () {
  77911. var _this = this;
  77912. this._physicsEngine.getImpostors().forEach(function (impostor) {
  77913. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  77914. if (!impostorForceAndContactPoint) {
  77915. return;
  77916. }
  77917. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77918. });
  77919. };
  77920. /*** Helpers ***/
  77921. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  77922. if (!this._cylinder) {
  77923. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  77924. height: this._height,
  77925. diameter: this._radius * 2,
  77926. }, this._scene);
  77927. this._cylinder.isVisible = false;
  77928. }
  77929. };
  77930. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  77931. var impostorObject = impostor.object;
  77932. this._prepareCylinder();
  77933. this._cylinder.position = this._cylinderPosition;
  77934. return this._cylinder.intersectsMesh(impostorObject, true);
  77935. };
  77936. return PhysicsVortexEvent;
  77937. }());
  77938. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  77939. /***** Enums *****/
  77940. /**
  77941. * The strenght of the force in correspondence to the distance of the affected object
  77942. */
  77943. var PhysicsRadialImpulseFalloff;
  77944. (function (PhysicsRadialImpulseFalloff) {
  77945. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  77946. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  77947. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  77948. /**
  77949. * The strenght of the force in correspondence to the distance of the affected object
  77950. */
  77951. var PhysicsUpdraftMode;
  77952. (function (PhysicsUpdraftMode) {
  77953. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  77954. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  77955. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  77956. })(BABYLON || (BABYLON = {}));
  77957. //# sourceMappingURL=babylon.physicsHelper.js.map
  77958. var BABYLON;
  77959. (function (BABYLON) {
  77960. var CannonJSPlugin = /** @class */ (function () {
  77961. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  77962. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  77963. if (iterations === void 0) { iterations = 10; }
  77964. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  77965. this.name = "CannonJSPlugin";
  77966. this._physicsMaterials = new Array();
  77967. this._fixedTimeStep = 1 / 60;
  77968. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  77969. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  77970. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  77971. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  77972. this._tmpPosition = BABYLON.Vector3.Zero();
  77973. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  77974. this._tmpUnityRotation = new BABYLON.Quaternion();
  77975. if (!this.isSupported()) {
  77976. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  77977. return;
  77978. }
  77979. this._extendNamespace();
  77980. this.world = new this.BJSCANNON.World();
  77981. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  77982. this.world.solver.iterations = iterations;
  77983. }
  77984. CannonJSPlugin.prototype.setGravity = function (gravity) {
  77985. this.world.gravity.copy(gravity);
  77986. };
  77987. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  77988. this._fixedTimeStep = timeStep;
  77989. };
  77990. CannonJSPlugin.prototype.getTimeStep = function () {
  77991. return this._fixedTimeStep;
  77992. };
  77993. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  77994. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  77995. };
  77996. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  77997. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  77998. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  77999. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  78000. };
  78001. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  78002. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  78003. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  78004. impostor.physicsBody.applyForce(impulse, worldPoint);
  78005. };
  78006. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  78007. //parent-child relationship. Does this impostor has a parent impostor?
  78008. if (impostor.parent) {
  78009. if (impostor.physicsBody) {
  78010. this.removePhysicsBody(impostor);
  78011. //TODO is that needed?
  78012. impostor.forceUpdate();
  78013. }
  78014. return;
  78015. }
  78016. //should a new body be created for this impostor?
  78017. if (impostor.isBodyInitRequired()) {
  78018. var shape = this._createShape(impostor);
  78019. //unregister events, if body is being changed
  78020. var oldBody = impostor.physicsBody;
  78021. if (oldBody) {
  78022. this.removePhysicsBody(impostor);
  78023. }
  78024. //create the body and material
  78025. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  78026. var bodyCreationObject = {
  78027. mass: impostor.getParam("mass"),
  78028. material: material
  78029. };
  78030. // A simple extend, in case native options were used.
  78031. var nativeOptions = impostor.getParam("nativeOptions");
  78032. for (var key in nativeOptions) {
  78033. if (nativeOptions.hasOwnProperty(key)) {
  78034. bodyCreationObject[key] = nativeOptions[key];
  78035. }
  78036. }
  78037. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  78038. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  78039. this.world.addEventListener("preStep", impostor.beforeStep);
  78040. this.world.addEventListener("postStep", impostor.afterStep);
  78041. impostor.physicsBody.addShape(shape);
  78042. this.world.add(impostor.physicsBody);
  78043. //try to keep the body moving in the right direction by taking old properties.
  78044. //Should be tested!
  78045. if (oldBody) {
  78046. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  78047. impostor.physicsBody[param].copy(oldBody[param]);
  78048. });
  78049. }
  78050. this._processChildMeshes(impostor);
  78051. }
  78052. //now update the body's transformation
  78053. this._updatePhysicsBodyTransformation(impostor);
  78054. };
  78055. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  78056. var _this = this;
  78057. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  78058. var currentRotation = mainImpostor.object.rotationQuaternion;
  78059. if (meshChildren.length) {
  78060. var processMesh = function (localPosition, mesh) {
  78061. if (!currentRotation || !mesh.rotationQuaternion) {
  78062. return;
  78063. }
  78064. var childImpostor = mesh.getPhysicsImpostor();
  78065. if (childImpostor) {
  78066. var parent = childImpostor.parent;
  78067. if (parent !== mainImpostor) {
  78068. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  78069. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  78070. if (childImpostor.physicsBody) {
  78071. _this.removePhysicsBody(childImpostor);
  78072. childImpostor.physicsBody = null;
  78073. }
  78074. childImpostor.parent = mainImpostor;
  78075. childImpostor.resetUpdateFlags();
  78076. 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));
  78077. //Add the mass of the children.
  78078. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  78079. }
  78080. }
  78081. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  78082. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  78083. };
  78084. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  78085. }
  78086. };
  78087. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  78088. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  78089. this.world.removeEventListener("preStep", impostor.beforeStep);
  78090. this.world.removeEventListener("postStep", impostor.afterStep);
  78091. this.world.remove(impostor.physicsBody);
  78092. };
  78093. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  78094. var mainBody = impostorJoint.mainImpostor.physicsBody;
  78095. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  78096. if (!mainBody || !connectedBody) {
  78097. return;
  78098. }
  78099. var constraint;
  78100. var jointData = impostorJoint.joint.jointData;
  78101. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  78102. var constraintData = {
  78103. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  78104. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  78105. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  78106. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  78107. maxForce: jointData.nativeParams.maxForce,
  78108. collideConnected: !!jointData.collision
  78109. };
  78110. switch (impostorJoint.joint.type) {
  78111. case BABYLON.PhysicsJoint.HingeJoint:
  78112. case BABYLON.PhysicsJoint.Hinge2Joint:
  78113. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  78114. break;
  78115. case BABYLON.PhysicsJoint.DistanceJoint:
  78116. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  78117. break;
  78118. case BABYLON.PhysicsJoint.SpringJoint:
  78119. var springData = jointData;
  78120. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  78121. restLength: springData.length,
  78122. stiffness: springData.stiffness,
  78123. damping: springData.damping,
  78124. localAnchorA: constraintData.pivotA,
  78125. localAnchorB: constraintData.pivotB
  78126. });
  78127. break;
  78128. case BABYLON.PhysicsJoint.LockJoint:
  78129. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  78130. break;
  78131. case BABYLON.PhysicsJoint.PointToPointJoint:
  78132. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  78133. default:
  78134. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  78135. break;
  78136. }
  78137. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  78138. constraint.collideConnected = !!jointData.collision;
  78139. impostorJoint.joint.physicsJoint = constraint;
  78140. //don't add spring as constraint, as it is not one.
  78141. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  78142. this.world.addConstraint(constraint);
  78143. }
  78144. else {
  78145. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  78146. constraint.applyForce();
  78147. });
  78148. }
  78149. };
  78150. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  78151. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  78152. };
  78153. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  78154. var index;
  78155. var mat;
  78156. for (index = 0; index < this._physicsMaterials.length; index++) {
  78157. mat = this._physicsMaterials[index];
  78158. if (mat.friction === friction && mat.restitution === restitution) {
  78159. return mat;
  78160. }
  78161. }
  78162. var currentMat = new this.BJSCANNON.Material(name);
  78163. currentMat.friction = friction;
  78164. currentMat.restitution = restitution;
  78165. this._physicsMaterials.push(currentMat);
  78166. return currentMat;
  78167. };
  78168. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  78169. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  78170. };
  78171. CannonJSPlugin.prototype._createShape = function (impostor) {
  78172. var object = impostor.object;
  78173. var returnValue;
  78174. var extendSize = impostor.getObjectExtendSize();
  78175. switch (impostor.type) {
  78176. case BABYLON.PhysicsImpostor.SphereImpostor:
  78177. var radiusX = extendSize.x;
  78178. var radiusY = extendSize.y;
  78179. var radiusZ = extendSize.z;
  78180. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  78181. break;
  78182. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  78183. case BABYLON.PhysicsImpostor.CylinderImpostor:
  78184. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  78185. break;
  78186. case BABYLON.PhysicsImpostor.BoxImpostor:
  78187. var box = extendSize.scale(0.5);
  78188. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  78189. break;
  78190. case BABYLON.PhysicsImpostor.PlaneImpostor:
  78191. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  78192. returnValue = new this.BJSCANNON.Plane();
  78193. break;
  78194. case BABYLON.PhysicsImpostor.MeshImpostor:
  78195. // should transform the vertex data to world coordinates!!
  78196. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  78197. var rawFaces = object.getIndices ? object.getIndices() : [];
  78198. if (!rawVerts)
  78199. return;
  78200. // get only scale! so the object could transform correctly.
  78201. var oldPosition = object.position.clone();
  78202. var oldRotation = object.rotation && object.rotation.clone();
  78203. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  78204. object.position.copyFromFloats(0, 0, 0);
  78205. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  78206. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  78207. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  78208. var transform = object.computeWorldMatrix(true);
  78209. // convert rawVerts to object space
  78210. var temp = new Array();
  78211. var index;
  78212. for (index = 0; index < rawVerts.length; index += 3) {
  78213. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  78214. }
  78215. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  78216. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  78217. //now set back the transformation!
  78218. object.position.copyFrom(oldPosition);
  78219. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  78220. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  78221. break;
  78222. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  78223. var oldPosition2 = object.position.clone();
  78224. var oldRotation2 = object.rotation && object.rotation.clone();
  78225. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  78226. object.position.copyFromFloats(0, 0, 0);
  78227. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  78228. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  78229. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  78230. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  78231. returnValue = this._createHeightmap(object);
  78232. object.position.copyFrom(oldPosition2);
  78233. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  78234. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  78235. object.computeWorldMatrix(true);
  78236. break;
  78237. case BABYLON.PhysicsImpostor.ParticleImpostor:
  78238. returnValue = new this.BJSCANNON.Particle();
  78239. break;
  78240. }
  78241. return returnValue;
  78242. };
  78243. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  78244. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  78245. var transform = object.computeWorldMatrix(true);
  78246. // convert rawVerts to object space
  78247. var temp = new Array();
  78248. var index;
  78249. for (index = 0; index < pos.length; index += 3) {
  78250. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  78251. }
  78252. pos = temp;
  78253. var matrix = new Array();
  78254. //For now pointDepth will not be used and will be automatically calculated.
  78255. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  78256. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  78257. var boundingInfo = object.getBoundingInfo();
  78258. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  78259. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  78260. var elementSize = dim * 2 / arraySize;
  78261. for (var i = 0; i < pos.length; i = i + 3) {
  78262. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  78263. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  78264. var y = -pos[i + 2] + minY;
  78265. if (!matrix[x]) {
  78266. matrix[x] = [];
  78267. }
  78268. if (!matrix[x][z]) {
  78269. matrix[x][z] = y;
  78270. }
  78271. matrix[x][z] = Math.max(y, matrix[x][z]);
  78272. }
  78273. for (var x = 0; x <= arraySize; ++x) {
  78274. if (!matrix[x]) {
  78275. var loc = 1;
  78276. while (!matrix[(x + loc) % arraySize]) {
  78277. loc++;
  78278. }
  78279. matrix[x] = matrix[(x + loc) % arraySize].slice();
  78280. //console.log("missing x", x);
  78281. }
  78282. for (var z = 0; z <= arraySize; ++z) {
  78283. if (!matrix[x][z]) {
  78284. var loc = 1;
  78285. var newValue;
  78286. while (newValue === undefined) {
  78287. newValue = matrix[x][(z + loc++) % arraySize];
  78288. }
  78289. matrix[x][z] = newValue;
  78290. }
  78291. }
  78292. }
  78293. var shape = new this.BJSCANNON.Heightfield(matrix, {
  78294. elementSize: elementSize
  78295. });
  78296. //For future reference, needed for body transformation
  78297. shape.minY = minY;
  78298. return shape;
  78299. };
  78300. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  78301. var object = impostor.object;
  78302. //make sure it is updated...
  78303. object.computeWorldMatrix && object.computeWorldMatrix(true);
  78304. // The delta between the mesh position and the mesh bounding box center
  78305. var bInfo = object.getBoundingInfo();
  78306. if (!bInfo)
  78307. return;
  78308. var center = impostor.getObjectCenter();
  78309. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  78310. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  78311. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  78312. this._tmpPosition.copyFrom(center);
  78313. var quaternion = object.rotationQuaternion;
  78314. if (!quaternion) {
  78315. return;
  78316. }
  78317. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  78318. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  78319. //-90 DEG in X, precalculated
  78320. quaternion = quaternion.multiply(this._minus90X);
  78321. //Invert! (Precalculated, 90 deg in X)
  78322. //No need to clone. this will never change.
  78323. impostor.setDeltaRotation(this._plus90X);
  78324. }
  78325. //If it is a heightfield, if should be centered.
  78326. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  78327. var mesh = object;
  78328. var boundingInfo = mesh.getBoundingInfo();
  78329. //calculate the correct body position:
  78330. var rotationQuaternion = mesh.rotationQuaternion;
  78331. mesh.rotationQuaternion = this._tmpUnityRotation;
  78332. mesh.computeWorldMatrix(true);
  78333. //get original center with no rotation
  78334. var c = center.clone();
  78335. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  78336. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  78337. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  78338. mesh.setPreTransformMatrix(p);
  78339. mesh.computeWorldMatrix(true);
  78340. //calculate the translation
  78341. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  78342. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  78343. //add it inverted to the delta
  78344. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  78345. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  78346. //rotation is back
  78347. mesh.rotationQuaternion = rotationQuaternion;
  78348. mesh.setPreTransformMatrix(oldPivot);
  78349. mesh.computeWorldMatrix(true);
  78350. }
  78351. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  78352. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  78353. //this._tmpPosition.copyFrom(object.position);
  78354. }
  78355. impostor.setDeltaPosition(this._tmpDeltaPosition);
  78356. //Now update the impostor object
  78357. impostor.physicsBody.position.copy(this._tmpPosition);
  78358. impostor.physicsBody.quaternion.copy(quaternion);
  78359. };
  78360. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  78361. impostor.object.position.copyFrom(impostor.physicsBody.position);
  78362. if (impostor.object.rotationQuaternion) {
  78363. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  78364. }
  78365. };
  78366. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  78367. impostor.physicsBody.position.copy(newPosition);
  78368. impostor.physicsBody.quaternion.copy(newRotation);
  78369. };
  78370. CannonJSPlugin.prototype.isSupported = function () {
  78371. return this.BJSCANNON !== undefined;
  78372. };
  78373. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  78374. impostor.physicsBody.velocity.copy(velocity);
  78375. };
  78376. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  78377. impostor.physicsBody.angularVelocity.copy(velocity);
  78378. };
  78379. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  78380. var v = impostor.physicsBody.velocity;
  78381. if (!v) {
  78382. return null;
  78383. }
  78384. return new BABYLON.Vector3(v.x, v.y, v.z);
  78385. };
  78386. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  78387. var v = impostor.physicsBody.angularVelocity;
  78388. if (!v) {
  78389. return null;
  78390. }
  78391. return new BABYLON.Vector3(v.x, v.y, v.z);
  78392. };
  78393. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  78394. impostor.physicsBody.mass = mass;
  78395. impostor.physicsBody.updateMassProperties();
  78396. };
  78397. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  78398. return impostor.physicsBody.mass;
  78399. };
  78400. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  78401. return impostor.physicsBody.material.friction;
  78402. };
  78403. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  78404. impostor.physicsBody.material.friction = friction;
  78405. };
  78406. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  78407. return impostor.physicsBody.material.restitution;
  78408. };
  78409. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  78410. impostor.physicsBody.material.restitution = restitution;
  78411. };
  78412. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  78413. impostor.physicsBody.sleep();
  78414. };
  78415. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  78416. impostor.physicsBody.wakeUp();
  78417. };
  78418. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  78419. joint.physicsJoint.distance = maxDistance;
  78420. };
  78421. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  78422. // if (!motorIndex) {
  78423. // joint.physicsJoint.enableMotor();
  78424. // }
  78425. // }
  78426. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  78427. // if (!motorIndex) {
  78428. // joint.physicsJoint.disableMotor();
  78429. // }
  78430. // }
  78431. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  78432. if (!motorIndex) {
  78433. joint.physicsJoint.enableMotor();
  78434. joint.physicsJoint.setMotorSpeed(speed);
  78435. if (maxForce) {
  78436. this.setLimit(joint, maxForce);
  78437. }
  78438. }
  78439. };
  78440. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  78441. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  78442. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  78443. };
  78444. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  78445. var body = impostor.physicsBody;
  78446. mesh.position.x = body.position.x;
  78447. mesh.position.y = body.position.y;
  78448. mesh.position.z = body.position.z;
  78449. if (mesh.rotationQuaternion) {
  78450. mesh.rotationQuaternion.x = body.quaternion.x;
  78451. mesh.rotationQuaternion.y = body.quaternion.y;
  78452. mesh.rotationQuaternion.z = body.quaternion.z;
  78453. mesh.rotationQuaternion.w = body.quaternion.w;
  78454. }
  78455. };
  78456. CannonJSPlugin.prototype.getRadius = function (impostor) {
  78457. var shape = impostor.physicsBody.shapes[0];
  78458. return shape.boundingSphereRadius;
  78459. };
  78460. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  78461. var shape = impostor.physicsBody.shapes[0];
  78462. result.x = shape.halfExtents.x * 2;
  78463. result.y = shape.halfExtents.y * 2;
  78464. result.z = shape.halfExtents.z * 2;
  78465. };
  78466. CannonJSPlugin.prototype.dispose = function () {
  78467. };
  78468. CannonJSPlugin.prototype._extendNamespace = function () {
  78469. //this will force cannon to execute at least one step when using interpolation
  78470. var step_tmp1 = new this.BJSCANNON.Vec3();
  78471. var Engine = this.BJSCANNON;
  78472. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  78473. maxSubSteps = maxSubSteps || 10;
  78474. timeSinceLastCalled = timeSinceLastCalled || 0;
  78475. if (timeSinceLastCalled === 0) {
  78476. this.internalStep(dt);
  78477. this.time += dt;
  78478. }
  78479. else {
  78480. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  78481. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  78482. var t0 = performance.now();
  78483. for (var i = 0; i !== internalSteps; i++) {
  78484. this.internalStep(dt);
  78485. if (performance.now() - t0 > dt * 1000) {
  78486. break;
  78487. }
  78488. }
  78489. this.time += timeSinceLastCalled;
  78490. var h = this.time % dt;
  78491. var h_div_dt = h / dt;
  78492. var interpvelo = step_tmp1;
  78493. var bodies = this.bodies;
  78494. for (var j = 0; j !== bodies.length; j++) {
  78495. var b = bodies[j];
  78496. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  78497. b.position.vsub(b.previousPosition, interpvelo);
  78498. interpvelo.scale(h_div_dt, interpvelo);
  78499. b.position.vadd(interpvelo, b.interpolatedPosition);
  78500. }
  78501. else {
  78502. b.interpolatedPosition.copy(b.position);
  78503. b.interpolatedQuaternion.copy(b.quaternion);
  78504. }
  78505. }
  78506. }
  78507. };
  78508. };
  78509. return CannonJSPlugin;
  78510. }());
  78511. BABYLON.CannonJSPlugin = CannonJSPlugin;
  78512. })(BABYLON || (BABYLON = {}));
  78513. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  78514. var BABYLON;
  78515. (function (BABYLON) {
  78516. var OimoJSPlugin = /** @class */ (function () {
  78517. function OimoJSPlugin(iterations) {
  78518. this.name = "OimoJSPlugin";
  78519. this._tmpImpostorsArray = [];
  78520. this._tmpPositionVector = BABYLON.Vector3.Zero();
  78521. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  78522. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  78523. this.world.worldscale(1);
  78524. this.world.clear();
  78525. //making sure no stats are calculated
  78526. this.world.isNoStat = true;
  78527. }
  78528. OimoJSPlugin.prototype.setGravity = function (gravity) {
  78529. this.world.gravity.copy(gravity);
  78530. };
  78531. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  78532. this.world.timeStep = timeStep;
  78533. };
  78534. OimoJSPlugin.prototype.getTimeStep = function () {
  78535. return this.world.timeStep;
  78536. };
  78537. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  78538. var _this = this;
  78539. impostors.forEach(function (impostor) {
  78540. impostor.beforeStep();
  78541. });
  78542. this.world.step();
  78543. impostors.forEach(function (impostor) {
  78544. impostor.afterStep();
  78545. //update the ordered impostors array
  78546. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  78547. });
  78548. //check for collisions
  78549. var contact = this.world.contacts;
  78550. while (contact !== null) {
  78551. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  78552. contact = contact.next;
  78553. continue;
  78554. }
  78555. //is this body colliding with any other? get the impostor
  78556. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  78557. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  78558. if (!mainImpostor || !collidingImpostor) {
  78559. contact = contact.next;
  78560. continue;
  78561. }
  78562. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  78563. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  78564. contact = contact.next;
  78565. }
  78566. };
  78567. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  78568. var mass = impostor.physicsBody.massInfo.mass;
  78569. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  78570. };
  78571. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  78572. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  78573. this.applyImpulse(impostor, force, contactPoint);
  78574. };
  78575. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  78576. var _this = this;
  78577. //parent-child relationship. Does this impostor has a parent impostor?
  78578. if (impostor.parent) {
  78579. if (impostor.physicsBody) {
  78580. this.removePhysicsBody(impostor);
  78581. //TODO is that needed?
  78582. impostor.forceUpdate();
  78583. }
  78584. return;
  78585. }
  78586. if (impostor.isBodyInitRequired()) {
  78587. var bodyConfig = {
  78588. name: impostor.uniqueId,
  78589. //Oimo must have mass, also for static objects.
  78590. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  78591. size: [],
  78592. type: [],
  78593. pos: [],
  78594. rot: [],
  78595. move: impostor.getParam("mass") !== 0,
  78596. //Supporting older versions of Oimo
  78597. world: this.world
  78598. };
  78599. var impostors = [impostor];
  78600. var addToArray = function (parent) {
  78601. if (!parent.getChildMeshes)
  78602. return;
  78603. parent.getChildMeshes().forEach(function (m) {
  78604. if (m.physicsImpostor) {
  78605. impostors.push(m.physicsImpostor);
  78606. //m.physicsImpostor._init();
  78607. }
  78608. });
  78609. };
  78610. addToArray(impostor.object);
  78611. var checkWithEpsilon_1 = function (value) {
  78612. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  78613. };
  78614. impostors.forEach(function (i) {
  78615. if (!impostor.object.rotationQuaternion) {
  78616. return;
  78617. }
  78618. //get the correct bounding box
  78619. var oldQuaternion = i.object.rotationQuaternion;
  78620. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  78621. x: impostor.object.rotationQuaternion.x,
  78622. y: impostor.object.rotationQuaternion.y,
  78623. z: impostor.object.rotationQuaternion.z,
  78624. s: impostor.object.rotationQuaternion.w
  78625. });
  78626. var extendSize = i.getObjectExtendSize();
  78627. if (i === impostor) {
  78628. var center = impostor.getObjectCenter();
  78629. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  78630. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  78631. //Can also use Array.prototype.push.apply
  78632. bodyConfig.pos.push(center.x);
  78633. bodyConfig.pos.push(center.y);
  78634. bodyConfig.pos.push(center.z);
  78635. //tmp solution
  78636. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  78637. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  78638. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  78639. }
  78640. else {
  78641. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  78642. bodyConfig.pos.push(localPosition.x);
  78643. bodyConfig.pos.push(localPosition.y);
  78644. bodyConfig.pos.push(localPosition.z);
  78645. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  78646. bodyConfig.rot.push(0);
  78647. bodyConfig.rot.push(0);
  78648. bodyConfig.rot.push(0);
  78649. }
  78650. // register mesh
  78651. switch (i.type) {
  78652. case BABYLON.PhysicsImpostor.ParticleImpostor:
  78653. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  78654. case BABYLON.PhysicsImpostor.SphereImpostor:
  78655. var radiusX = extendSize.x;
  78656. var radiusY = extendSize.y;
  78657. var radiusZ = extendSize.z;
  78658. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  78659. bodyConfig.type.push('sphere');
  78660. //due to the way oimo works with compounds, add 3 times
  78661. bodyConfig.size.push(size);
  78662. bodyConfig.size.push(size);
  78663. bodyConfig.size.push(size);
  78664. break;
  78665. case BABYLON.PhysicsImpostor.CylinderImpostor:
  78666. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  78667. var sizeY = checkWithEpsilon_1(extendSize.y);
  78668. bodyConfig.type.push('cylinder');
  78669. bodyConfig.size.push(sizeX);
  78670. bodyConfig.size.push(sizeY);
  78671. //due to the way oimo works with compounds, add one more value.
  78672. bodyConfig.size.push(sizeY);
  78673. break;
  78674. case BABYLON.PhysicsImpostor.PlaneImpostor:
  78675. case BABYLON.PhysicsImpostor.BoxImpostor:
  78676. default:
  78677. var sizeX = checkWithEpsilon_1(extendSize.x);
  78678. var sizeY = checkWithEpsilon_1(extendSize.y);
  78679. var sizeZ = checkWithEpsilon_1(extendSize.z);
  78680. bodyConfig.type.push('box');
  78681. bodyConfig.size.push(sizeX);
  78682. bodyConfig.size.push(sizeY);
  78683. bodyConfig.size.push(sizeZ);
  78684. break;
  78685. }
  78686. //actually not needed, but hey...
  78687. i.object.rotationQuaternion = oldQuaternion;
  78688. });
  78689. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  78690. }
  78691. else {
  78692. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  78693. }
  78694. impostor.setDeltaPosition(this._tmpPositionVector);
  78695. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  78696. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  78697. };
  78698. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  78699. //impostor.physicsBody.dispose();
  78700. //Same as : (older oimo versions)
  78701. this.world.removeRigidBody(impostor.physicsBody);
  78702. };
  78703. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  78704. var mainBody = impostorJoint.mainImpostor.physicsBody;
  78705. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  78706. if (!mainBody || !connectedBody) {
  78707. return;
  78708. }
  78709. var jointData = impostorJoint.joint.jointData;
  78710. var options = jointData.nativeParams || {};
  78711. var type;
  78712. var nativeJointData = {
  78713. body1: mainBody,
  78714. body2: connectedBody,
  78715. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  78716. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  78717. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  78718. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  78719. min: options.min,
  78720. max: options.max,
  78721. collision: options.collision || jointData.collision,
  78722. spring: options.spring,
  78723. //supporting older version of Oimo
  78724. world: this.world
  78725. };
  78726. switch (impostorJoint.joint.type) {
  78727. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  78728. type = "jointBall";
  78729. break;
  78730. case BABYLON.PhysicsJoint.SpringJoint:
  78731. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  78732. var springData = jointData;
  78733. nativeJointData.min = springData.length || nativeJointData.min;
  78734. //Max should also be set, just make sure it is at least min
  78735. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  78736. case BABYLON.PhysicsJoint.DistanceJoint:
  78737. type = "jointDistance";
  78738. nativeJointData.max = jointData.maxDistance;
  78739. break;
  78740. case BABYLON.PhysicsJoint.PrismaticJoint:
  78741. type = "jointPrisme";
  78742. break;
  78743. case BABYLON.PhysicsJoint.SliderJoint:
  78744. type = "jointSlide";
  78745. break;
  78746. case BABYLON.PhysicsJoint.WheelJoint:
  78747. type = "jointWheel";
  78748. break;
  78749. case BABYLON.PhysicsJoint.HingeJoint:
  78750. default:
  78751. type = "jointHinge";
  78752. break;
  78753. }
  78754. nativeJointData.type = type;
  78755. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  78756. };
  78757. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  78758. //Bug in Oimo prevents us from disposing a joint in the playground
  78759. //joint.joint.physicsJoint.dispose();
  78760. //So we will bruteforce it!
  78761. try {
  78762. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  78763. }
  78764. catch (e) {
  78765. BABYLON.Tools.Warn(e);
  78766. }
  78767. };
  78768. OimoJSPlugin.prototype.isSupported = function () {
  78769. return this.BJSOIMO !== undefined;
  78770. };
  78771. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  78772. if (!impostor.physicsBody.sleeping) {
  78773. //TODO check that
  78774. if (impostor.physicsBody.shapes.next) {
  78775. var parentShape = this._getLastShape(impostor.physicsBody);
  78776. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  78777. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  78778. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  78779. }
  78780. else {
  78781. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  78782. }
  78783. if (impostor.object.rotationQuaternion) {
  78784. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  78785. impostor.object.rotationQuaternion.normalize();
  78786. }
  78787. }
  78788. };
  78789. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  78790. var body = impostor.physicsBody;
  78791. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  78792. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  78793. body.syncShapes();
  78794. body.awake();
  78795. };
  78796. OimoJSPlugin.prototype._getLastShape = function (body) {
  78797. var lastShape = body.shapes;
  78798. while (lastShape.next) {
  78799. lastShape = lastShape.next;
  78800. }
  78801. return lastShape;
  78802. };
  78803. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  78804. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  78805. };
  78806. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  78807. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  78808. };
  78809. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  78810. var v = impostor.physicsBody.linearVelocity;
  78811. if (!v) {
  78812. return null;
  78813. }
  78814. return new BABYLON.Vector3(v.x, v.y, v.z);
  78815. };
  78816. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  78817. var v = impostor.physicsBody.angularVelocity;
  78818. if (!v) {
  78819. return null;
  78820. }
  78821. return new BABYLON.Vector3(v.x, v.y, v.z);
  78822. };
  78823. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  78824. var staticBody = mass === 0;
  78825. //this will actually set the body's density and not its mass.
  78826. //But this is how oimo treats the mass variable.
  78827. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  78828. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  78829. };
  78830. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  78831. return impostor.physicsBody.shapes.density;
  78832. };
  78833. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  78834. return impostor.physicsBody.shapes.friction;
  78835. };
  78836. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  78837. impostor.physicsBody.shapes.friction = friction;
  78838. };
  78839. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  78840. return impostor.physicsBody.shapes.restitution;
  78841. };
  78842. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  78843. impostor.physicsBody.shapes.restitution = restitution;
  78844. };
  78845. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  78846. impostor.physicsBody.sleep();
  78847. };
  78848. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  78849. impostor.physicsBody.awake();
  78850. };
  78851. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  78852. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  78853. if (minDistance !== void 0) {
  78854. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  78855. }
  78856. };
  78857. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  78858. //TODO separate rotational and transational motors.
  78859. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  78860. if (motor) {
  78861. motor.setMotor(speed, maxForce);
  78862. }
  78863. };
  78864. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  78865. //TODO separate rotational and transational motors.
  78866. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  78867. if (motor) {
  78868. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  78869. }
  78870. };
  78871. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  78872. var body = impostor.physicsBody;
  78873. mesh.position.x = body.position.x;
  78874. mesh.position.y = body.position.y;
  78875. mesh.position.z = body.position.z;
  78876. if (mesh.rotationQuaternion) {
  78877. mesh.rotationQuaternion.x = body.orientation.x;
  78878. mesh.rotationQuaternion.y = body.orientation.y;
  78879. mesh.rotationQuaternion.z = body.orientation.z;
  78880. mesh.rotationQuaternion.w = body.orientation.s;
  78881. }
  78882. };
  78883. OimoJSPlugin.prototype.getRadius = function (impostor) {
  78884. return impostor.physicsBody.shapes.radius;
  78885. };
  78886. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  78887. var shape = impostor.physicsBody.shapes;
  78888. result.x = shape.halfWidth * 2;
  78889. result.y = shape.halfHeight * 2;
  78890. result.z = shape.halfDepth * 2;
  78891. };
  78892. OimoJSPlugin.prototype.dispose = function () {
  78893. this.world.clear();
  78894. };
  78895. return OimoJSPlugin;
  78896. }());
  78897. BABYLON.OimoJSPlugin = OimoJSPlugin;
  78898. })(BABYLON || (BABYLON = {}));
  78899. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  78900. var BABYLON;
  78901. (function (BABYLON) {
  78902. /*
  78903. * Based on jsTGALoader - Javascript loader for TGA file
  78904. * By Vincent Thibault
  78905. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  78906. */
  78907. var TGATools = /** @class */ (function () {
  78908. function TGATools() {
  78909. }
  78910. TGATools.GetTGAHeader = function (data) {
  78911. var offset = 0;
  78912. var header = {
  78913. id_length: data[offset++],
  78914. colormap_type: data[offset++],
  78915. image_type: data[offset++],
  78916. colormap_index: data[offset++] | data[offset++] << 8,
  78917. colormap_length: data[offset++] | data[offset++] << 8,
  78918. colormap_size: data[offset++],
  78919. origin: [
  78920. data[offset++] | data[offset++] << 8,
  78921. data[offset++] | data[offset++] << 8
  78922. ],
  78923. width: data[offset++] | data[offset++] << 8,
  78924. height: data[offset++] | data[offset++] << 8,
  78925. pixel_size: data[offset++],
  78926. flags: data[offset++]
  78927. };
  78928. return header;
  78929. };
  78930. TGATools.UploadContent = function (gl, data) {
  78931. // Not enough data to contain header ?
  78932. if (data.length < 19) {
  78933. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  78934. return;
  78935. }
  78936. // Read Header
  78937. var offset = 18;
  78938. var header = TGATools.GetTGAHeader(data);
  78939. // Assume it's a valid Targa file.
  78940. if (header.id_length + offset > data.length) {
  78941. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  78942. return;
  78943. }
  78944. // Skip not needed data
  78945. offset += header.id_length;
  78946. var use_rle = false;
  78947. var use_pal = false;
  78948. var use_grey = false;
  78949. // Get some informations.
  78950. switch (header.image_type) {
  78951. case TGATools._TYPE_RLE_INDEXED:
  78952. use_rle = true;
  78953. case TGATools._TYPE_INDEXED:
  78954. use_pal = true;
  78955. break;
  78956. case TGATools._TYPE_RLE_RGB:
  78957. use_rle = true;
  78958. case TGATools._TYPE_RGB:
  78959. // use_rgb = true;
  78960. break;
  78961. case TGATools._TYPE_RLE_GREY:
  78962. use_rle = true;
  78963. case TGATools._TYPE_GREY:
  78964. use_grey = true;
  78965. break;
  78966. }
  78967. var pixel_data;
  78968. // var numAlphaBits = header.flags & 0xf;
  78969. var pixel_size = header.pixel_size >> 3;
  78970. var pixel_total = header.width * header.height * pixel_size;
  78971. // Read palettes
  78972. var palettes;
  78973. if (use_pal) {
  78974. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  78975. }
  78976. // Read LRE
  78977. if (use_rle) {
  78978. pixel_data = new Uint8Array(pixel_total);
  78979. var c, count, i;
  78980. var localOffset = 0;
  78981. var pixels = new Uint8Array(pixel_size);
  78982. while (offset < pixel_total && localOffset < pixel_total) {
  78983. c = data[offset++];
  78984. count = (c & 0x7f) + 1;
  78985. // RLE pixels
  78986. if (c & 0x80) {
  78987. // Bind pixel tmp array
  78988. for (i = 0; i < pixel_size; ++i) {
  78989. pixels[i] = data[offset++];
  78990. }
  78991. // Copy pixel array
  78992. for (i = 0; i < count; ++i) {
  78993. pixel_data.set(pixels, localOffset + i * pixel_size);
  78994. }
  78995. localOffset += pixel_size * count;
  78996. }
  78997. else {
  78998. count *= pixel_size;
  78999. for (i = 0; i < count; ++i) {
  79000. pixel_data[localOffset + i] = data[offset++];
  79001. }
  79002. localOffset += count;
  79003. }
  79004. }
  79005. }
  79006. else {
  79007. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  79008. }
  79009. // Load to texture
  79010. var x_start, y_start, x_step, y_step, y_end, x_end;
  79011. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  79012. default:
  79013. case TGATools._ORIGIN_UL:
  79014. x_start = 0;
  79015. x_step = 1;
  79016. x_end = header.width;
  79017. y_start = 0;
  79018. y_step = 1;
  79019. y_end = header.height;
  79020. break;
  79021. case TGATools._ORIGIN_BL:
  79022. x_start = 0;
  79023. x_step = 1;
  79024. x_end = header.width;
  79025. y_start = header.height - 1;
  79026. y_step = -1;
  79027. y_end = -1;
  79028. break;
  79029. case TGATools._ORIGIN_UR:
  79030. x_start = header.width - 1;
  79031. x_step = -1;
  79032. x_end = -1;
  79033. y_start = 0;
  79034. y_step = 1;
  79035. y_end = header.height;
  79036. break;
  79037. case TGATools._ORIGIN_BR:
  79038. x_start = header.width - 1;
  79039. x_step = -1;
  79040. x_end = -1;
  79041. y_start = header.height - 1;
  79042. y_step = -1;
  79043. y_end = -1;
  79044. break;
  79045. }
  79046. // Load the specify method
  79047. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  79048. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  79049. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  79050. };
  79051. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79052. var image = pixel_data, colormap = palettes;
  79053. var width = header.width, height = header.height;
  79054. var color, i = 0, x, y;
  79055. var imageData = new Uint8Array(width * height * 4);
  79056. for (y = y_start; y !== y_end; y += y_step) {
  79057. for (x = x_start; x !== x_end; x += x_step, i++) {
  79058. color = image[i];
  79059. imageData[(x + width * y) * 4 + 3] = 255;
  79060. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  79061. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  79062. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  79063. }
  79064. }
  79065. return imageData;
  79066. };
  79067. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79068. var image = pixel_data;
  79069. var width = header.width, height = header.height;
  79070. var color, i = 0, x, y;
  79071. var imageData = new Uint8Array(width * height * 4);
  79072. for (y = y_start; y !== y_end; y += y_step) {
  79073. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  79074. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  79075. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  79076. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  79077. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  79078. imageData[(x + width * y) * 4 + 0] = r;
  79079. imageData[(x + width * y) * 4 + 1] = g;
  79080. imageData[(x + width * y) * 4 + 2] = b;
  79081. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  79082. }
  79083. }
  79084. return imageData;
  79085. };
  79086. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79087. var image = pixel_data;
  79088. var width = header.width, height = header.height;
  79089. var i = 0, x, y;
  79090. var imageData = new Uint8Array(width * height * 4);
  79091. for (y = y_start; y !== y_end; y += y_step) {
  79092. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  79093. imageData[(x + width * y) * 4 + 3] = 255;
  79094. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79095. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  79096. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  79097. }
  79098. }
  79099. return imageData;
  79100. };
  79101. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79102. var image = pixel_data;
  79103. var width = header.width, height = header.height;
  79104. var i = 0, x, y;
  79105. var imageData = new Uint8Array(width * height * 4);
  79106. for (y = y_start; y !== y_end; y += y_step) {
  79107. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  79108. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79109. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  79110. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  79111. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  79112. }
  79113. }
  79114. return imageData;
  79115. };
  79116. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79117. var image = pixel_data;
  79118. var width = header.width, height = header.height;
  79119. var color, i = 0, x, y;
  79120. var imageData = new Uint8Array(width * height * 4);
  79121. for (y = y_start; y !== y_end; y += y_step) {
  79122. for (x = x_start; x !== x_end; x += x_step, i++) {
  79123. color = image[i];
  79124. imageData[(x + width * y) * 4 + 0] = color;
  79125. imageData[(x + width * y) * 4 + 1] = color;
  79126. imageData[(x + width * y) * 4 + 2] = color;
  79127. imageData[(x + width * y) * 4 + 3] = 255;
  79128. }
  79129. }
  79130. return imageData;
  79131. };
  79132. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79133. var image = pixel_data;
  79134. var width = header.width, height = header.height;
  79135. var i = 0, x, y;
  79136. var imageData = new Uint8Array(width * height * 4);
  79137. for (y = y_start; y !== y_end; y += y_step) {
  79138. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  79139. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  79140. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  79141. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79142. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  79143. }
  79144. }
  79145. return imageData;
  79146. };
  79147. //private static _TYPE_NO_DATA = 0;
  79148. TGATools._TYPE_INDEXED = 1;
  79149. TGATools._TYPE_RGB = 2;
  79150. TGATools._TYPE_GREY = 3;
  79151. TGATools._TYPE_RLE_INDEXED = 9;
  79152. TGATools._TYPE_RLE_RGB = 10;
  79153. TGATools._TYPE_RLE_GREY = 11;
  79154. TGATools._ORIGIN_MASK = 0x30;
  79155. TGATools._ORIGIN_SHIFT = 0x04;
  79156. TGATools._ORIGIN_BL = 0x00;
  79157. TGATools._ORIGIN_BR = 0x01;
  79158. TGATools._ORIGIN_UL = 0x02;
  79159. TGATools._ORIGIN_UR = 0x03;
  79160. return TGATools;
  79161. }());
  79162. BABYLON.TGATools = TGATools;
  79163. })(BABYLON || (BABYLON = {}));
  79164. //# sourceMappingURL=babylon.tga.js.map
  79165. var BABYLON;
  79166. (function (BABYLON) {
  79167. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  79168. // All values and structures referenced from:
  79169. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  79170. var DDS_MAGIC = 0x20534444;
  79171. var
  79172. //DDSD_CAPS = 0x1,
  79173. //DDSD_HEIGHT = 0x2,
  79174. //DDSD_WIDTH = 0x4,
  79175. //DDSD_PITCH = 0x8,
  79176. //DDSD_PIXELFORMAT = 0x1000,
  79177. DDSD_MIPMAPCOUNT = 0x20000;
  79178. //DDSD_LINEARSIZE = 0x80000,
  79179. //DDSD_DEPTH = 0x800000;
  79180. // var DDSCAPS_COMPLEX = 0x8,
  79181. // DDSCAPS_MIPMAP = 0x400000,
  79182. // DDSCAPS_TEXTURE = 0x1000;
  79183. var DDSCAPS2_CUBEMAP = 0x200;
  79184. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  79185. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  79186. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  79187. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  79188. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  79189. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  79190. // DDSCAPS2_VOLUME = 0x200000;
  79191. var
  79192. //DDPF_ALPHAPIXELS = 0x1,
  79193. //DDPF_ALPHA = 0x2,
  79194. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  79195. //DDPF_YUV = 0x200,
  79196. DDPF_LUMINANCE = 0x20000;
  79197. function FourCCToInt32(value) {
  79198. return value.charCodeAt(0) +
  79199. (value.charCodeAt(1) << 8) +
  79200. (value.charCodeAt(2) << 16) +
  79201. (value.charCodeAt(3) << 24);
  79202. }
  79203. function Int32ToFourCC(value) {
  79204. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  79205. }
  79206. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  79207. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  79208. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  79209. var FOURCC_DX10 = FourCCToInt32("DX10");
  79210. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  79211. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  79212. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  79213. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  79214. var headerLengthInt = 31; // The header length in 32 bit ints
  79215. // Offsets into the header array
  79216. var off_magic = 0;
  79217. var off_size = 1;
  79218. var off_flags = 2;
  79219. var off_height = 3;
  79220. var off_width = 4;
  79221. var off_mipmapCount = 7;
  79222. var off_pfFlags = 20;
  79223. var off_pfFourCC = 21;
  79224. var off_RGBbpp = 22;
  79225. var off_RMask = 23;
  79226. var off_GMask = 24;
  79227. var off_BMask = 25;
  79228. var off_AMask = 26;
  79229. // var off_caps1 = 27;
  79230. var off_caps2 = 28;
  79231. // var off_caps3 = 29;
  79232. // var off_caps4 = 30;
  79233. var off_dxgiFormat = 32;
  79234. ;
  79235. var DDSTools = /** @class */ (function () {
  79236. function DDSTools() {
  79237. }
  79238. DDSTools.GetDDSInfo = function (arrayBuffer) {
  79239. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  79240. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  79241. var mipmapCount = 1;
  79242. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  79243. mipmapCount = Math.max(1, header[off_mipmapCount]);
  79244. }
  79245. var fourCC = header[off_pfFourCC];
  79246. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  79247. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79248. switch (fourCC) {
  79249. case FOURCC_D3DFMT_R16G16B16A16F:
  79250. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79251. break;
  79252. case FOURCC_D3DFMT_R32G32B32A32F:
  79253. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79254. break;
  79255. case FOURCC_DX10:
  79256. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  79257. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79258. break;
  79259. }
  79260. }
  79261. return {
  79262. width: header[off_width],
  79263. height: header[off_height],
  79264. mipmapCount: mipmapCount,
  79265. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  79266. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  79267. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  79268. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  79269. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  79270. dxgiFormat: dxgiFormat,
  79271. textureType: textureType
  79272. };
  79273. };
  79274. DDSTools._ToHalfFloat = function (value) {
  79275. if (!DDSTools._FloatView) {
  79276. DDSTools._FloatView = new Float32Array(1);
  79277. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  79278. }
  79279. DDSTools._FloatView[0] = value;
  79280. var x = DDSTools._Int32View[0];
  79281. var bits = (x >> 16) & 0x8000; /* Get the sign */
  79282. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  79283. var e = (x >> 23) & 0xff; /* Using int is faster here */
  79284. /* If zero, or denormal, or exponent underflows too much for a denormal
  79285. * half, return signed zero. */
  79286. if (e < 103) {
  79287. return bits;
  79288. }
  79289. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  79290. if (e > 142) {
  79291. bits |= 0x7c00;
  79292. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  79293. * not Inf, so make sure we set one mantissa bit too. */
  79294. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  79295. return bits;
  79296. }
  79297. /* If exponent underflows but not too much, return a denormal */
  79298. if (e < 113) {
  79299. m |= 0x0800;
  79300. /* Extra rounding may overflow and set mantissa to 0 and exponent
  79301. * to 1, which is OK. */
  79302. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  79303. return bits;
  79304. }
  79305. bits |= ((e - 112) << 10) | (m >> 1);
  79306. bits += m & 1;
  79307. return bits;
  79308. };
  79309. DDSTools._FromHalfFloat = function (value) {
  79310. var s = (value & 0x8000) >> 15;
  79311. var e = (value & 0x7C00) >> 10;
  79312. var f = value & 0x03FF;
  79313. if (e === 0) {
  79314. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  79315. }
  79316. else if (e == 0x1F) {
  79317. return f ? NaN : ((s ? -1 : 1) * Infinity);
  79318. }
  79319. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  79320. };
  79321. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79322. var destArray = new Float32Array(dataLength);
  79323. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  79324. var index = 0;
  79325. for (var y = 0; y < height; y++) {
  79326. for (var x = 0; x < width; x++) {
  79327. var srcPos = (x + y * width) * 4;
  79328. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  79329. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  79330. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  79331. if (DDSTools.StoreLODInAlphaChannel) {
  79332. destArray[index + 3] = lod;
  79333. }
  79334. else {
  79335. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  79336. }
  79337. index += 4;
  79338. }
  79339. }
  79340. return destArray;
  79341. };
  79342. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79343. if (DDSTools.StoreLODInAlphaChannel) {
  79344. var destArray = new Uint16Array(dataLength);
  79345. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  79346. var index = 0;
  79347. for (var y = 0; y < height; y++) {
  79348. for (var x = 0; x < width; x++) {
  79349. var srcPos = (x + y * width) * 4;
  79350. destArray[index] = srcData[srcPos];
  79351. destArray[index + 1] = srcData[srcPos + 1];
  79352. destArray[index + 2] = srcData[srcPos + 2];
  79353. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  79354. index += 4;
  79355. }
  79356. }
  79357. return destArray;
  79358. }
  79359. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  79360. };
  79361. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79362. if (DDSTools.StoreLODInAlphaChannel) {
  79363. var destArray = new Float32Array(dataLength);
  79364. var srcData = new Float32Array(arrayBuffer, dataOffset);
  79365. var index = 0;
  79366. for (var y = 0; y < height; y++) {
  79367. for (var x = 0; x < width; x++) {
  79368. var srcPos = (x + y * width) * 4;
  79369. destArray[index] = srcData[srcPos];
  79370. destArray[index + 1] = srcData[srcPos + 1];
  79371. destArray[index + 2] = srcData[srcPos + 2];
  79372. destArray[index + 3] = lod;
  79373. index += 4;
  79374. }
  79375. }
  79376. return destArray;
  79377. }
  79378. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  79379. };
  79380. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79381. var destArray = new Uint8Array(dataLength);
  79382. var srcData = new Float32Array(arrayBuffer, dataOffset);
  79383. var index = 0;
  79384. for (var y = 0; y < height; y++) {
  79385. for (var x = 0; x < width; x++) {
  79386. var srcPos = (x + y * width) * 4;
  79387. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  79388. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  79389. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  79390. if (DDSTools.StoreLODInAlphaChannel) {
  79391. destArray[index + 3] = lod;
  79392. }
  79393. else {
  79394. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  79395. }
  79396. index += 4;
  79397. }
  79398. }
  79399. return destArray;
  79400. };
  79401. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79402. var destArray = new Uint8Array(dataLength);
  79403. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  79404. var index = 0;
  79405. for (var y = 0; y < height; y++) {
  79406. for (var x = 0; x < width; x++) {
  79407. var srcPos = (x + y * width) * 4;
  79408. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  79409. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  79410. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  79411. if (DDSTools.StoreLODInAlphaChannel) {
  79412. destArray[index + 3] = lod;
  79413. }
  79414. else {
  79415. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  79416. }
  79417. index += 4;
  79418. }
  79419. }
  79420. return destArray;
  79421. };
  79422. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  79423. var byteArray = new Uint8Array(dataLength);
  79424. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79425. var index = 0;
  79426. for (var y = 0; y < height; y++) {
  79427. for (var x = 0; x < width; x++) {
  79428. var srcPos = (x + y * width) * 4;
  79429. byteArray[index] = srcData[srcPos + rOffset];
  79430. byteArray[index + 1] = srcData[srcPos + gOffset];
  79431. byteArray[index + 2] = srcData[srcPos + bOffset];
  79432. byteArray[index + 3] = srcData[srcPos + aOffset];
  79433. index += 4;
  79434. }
  79435. }
  79436. return byteArray;
  79437. };
  79438. DDSTools._ExtractLongWordOrder = function (value) {
  79439. if (value === 0 || value === 255 || value === -16777216) {
  79440. return 0;
  79441. }
  79442. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  79443. };
  79444. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  79445. var byteArray = new Uint8Array(dataLength);
  79446. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79447. var index = 0;
  79448. for (var y = 0; y < height; y++) {
  79449. for (var x = 0; x < width; x++) {
  79450. var srcPos = (x + y * width) * 3;
  79451. byteArray[index] = srcData[srcPos + rOffset];
  79452. byteArray[index + 1] = srcData[srcPos + gOffset];
  79453. byteArray[index + 2] = srcData[srcPos + bOffset];
  79454. index += 3;
  79455. }
  79456. }
  79457. return byteArray;
  79458. };
  79459. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  79460. var byteArray = new Uint8Array(dataLength);
  79461. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79462. var index = 0;
  79463. for (var y = 0; y < height; y++) {
  79464. for (var x = 0; x < width; x++) {
  79465. var srcPos = (x + y * width);
  79466. byteArray[index] = srcData[srcPos];
  79467. index++;
  79468. }
  79469. }
  79470. return byteArray;
  79471. };
  79472. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  79473. if (lodIndex === void 0) { lodIndex = -1; }
  79474. var ext = engine.getCaps().s3tc;
  79475. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  79476. var fourCC, width, height, dataLength = 0, dataOffset;
  79477. var byteArray, mipmapCount, mip;
  79478. var internalFormat = 0;
  79479. var format = 0;
  79480. var blockBytes = 1;
  79481. if (header[off_magic] !== DDS_MAGIC) {
  79482. BABYLON.Tools.Error("Invalid magic number in DDS header");
  79483. return;
  79484. }
  79485. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  79486. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  79487. return;
  79488. }
  79489. if (info.isCompressed && !ext) {
  79490. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  79491. return;
  79492. }
  79493. var bpp = header[off_RGBbpp];
  79494. dataOffset = header[off_size] + 4;
  79495. var computeFormats = false;
  79496. if (info.isFourCC) {
  79497. fourCC = header[off_pfFourCC];
  79498. switch (fourCC) {
  79499. case FOURCC_DXT1:
  79500. blockBytes = 8;
  79501. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  79502. break;
  79503. case FOURCC_DXT3:
  79504. blockBytes = 16;
  79505. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  79506. break;
  79507. case FOURCC_DXT5:
  79508. blockBytes = 16;
  79509. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  79510. break;
  79511. case FOURCC_D3DFMT_R16G16B16A16F:
  79512. computeFormats = true;
  79513. break;
  79514. case FOURCC_D3DFMT_R32G32B32A32F:
  79515. computeFormats = true;
  79516. break;
  79517. case FOURCC_DX10:
  79518. // There is an additionnal header so dataOffset need to be changed
  79519. dataOffset += 5 * 4; // 5 uints
  79520. var supported = false;
  79521. switch (info.dxgiFormat) {
  79522. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  79523. computeFormats = true;
  79524. supported = true;
  79525. break;
  79526. case DXGI_FORMAT_B8G8R8X8_UNORM:
  79527. info.isRGB = true;
  79528. info.isFourCC = false;
  79529. bpp = 32;
  79530. supported = true;
  79531. break;
  79532. }
  79533. if (supported) {
  79534. break;
  79535. }
  79536. default:
  79537. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  79538. return;
  79539. }
  79540. }
  79541. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  79542. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  79543. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  79544. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  79545. if (computeFormats) {
  79546. format = engine._getWebGLTextureType(info.textureType);
  79547. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79548. }
  79549. mipmapCount = 1;
  79550. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  79551. mipmapCount = Math.max(1, header[off_mipmapCount]);
  79552. }
  79553. for (var face = 0; face < faces; face++) {
  79554. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  79555. width = header[off_width];
  79556. height = header[off_height];
  79557. for (mip = 0; mip < mipmapCount; ++mip) {
  79558. if (lodIndex === -1 || lodIndex === mip) {
  79559. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  79560. var i = (lodIndex === -1) ? mip : 0;
  79561. if (!info.isCompressed && info.isFourCC) {
  79562. dataLength = width * height * 4;
  79563. var floatArray = null;
  79564. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  79565. if (bpp === 128) {
  79566. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79567. }
  79568. else if (bpp === 64) {
  79569. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79570. }
  79571. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79572. format = engine._getWebGLTextureType(info.textureType);
  79573. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79574. }
  79575. else {
  79576. if (bpp === 128) {
  79577. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79578. }
  79579. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  79580. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79581. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79582. format = engine._getWebGLTextureType(info.textureType);
  79583. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79584. }
  79585. else {
  79586. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79587. }
  79588. }
  79589. if (floatArray) {
  79590. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  79591. }
  79592. }
  79593. else if (info.isRGB) {
  79594. if (bpp === 24) {
  79595. dataLength = width * height * 3;
  79596. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  79597. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  79598. }
  79599. else {
  79600. dataLength = width * height * 4;
  79601. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  79602. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  79603. }
  79604. }
  79605. else if (info.isLuminance) {
  79606. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  79607. var unpaddedRowSize = width;
  79608. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  79609. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  79610. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  79611. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  79612. }
  79613. else {
  79614. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  79615. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  79616. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  79617. }
  79618. }
  79619. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  79620. width *= 0.5;
  79621. height *= 0.5;
  79622. width = Math.max(1.0, width);
  79623. height = Math.max(1.0, height);
  79624. }
  79625. if (currentFace !== undefined) {
  79626. // Loading a single face
  79627. break;
  79628. }
  79629. }
  79630. };
  79631. DDSTools.StoreLODInAlphaChannel = false;
  79632. return DDSTools;
  79633. }());
  79634. BABYLON.DDSTools = DDSTools;
  79635. })(BABYLON || (BABYLON = {}));
  79636. //# sourceMappingURL=babylon.dds.js.map
  79637. var BABYLON;
  79638. (function (BABYLON) {
  79639. /**
  79640. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  79641. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  79642. */
  79643. var KhronosTextureContainer = /** @class */ (function () {
  79644. /**
  79645. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  79646. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  79647. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  79648. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  79649. */
  79650. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  79651. this.arrayBuffer = arrayBuffer;
  79652. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  79653. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  79654. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  79655. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  79656. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  79657. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  79658. BABYLON.Tools.Error("texture missing KTX identifier");
  79659. return;
  79660. }
  79661. // load the reset of the header in native 32 bit int
  79662. var header = new Int32Array(this.arrayBuffer, 12, 13);
  79663. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  79664. var oppositeEndianess = header[0] === 0x01020304;
  79665. // read all the header elements in order they exist in the file, without modification (sans endainness)
  79666. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  79667. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  79668. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  79669. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  79670. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  79671. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  79672. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  79673. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  79674. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  79675. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  79676. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  79677. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  79678. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  79679. if (this.glType !== 0) {
  79680. BABYLON.Tools.Error("only compressed formats currently supported");
  79681. return;
  79682. }
  79683. else {
  79684. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  79685. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  79686. }
  79687. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  79688. BABYLON.Tools.Error("only 2D textures currently supported");
  79689. return;
  79690. }
  79691. if (this.numberOfArrayElements !== 0) {
  79692. BABYLON.Tools.Error("texture arrays not currently supported");
  79693. return;
  79694. }
  79695. if (this.numberOfFaces !== facesExpected) {
  79696. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  79697. return;
  79698. }
  79699. // we now have a completely validated file, so could use existence of loadType as success
  79700. // would need to make this more elaborate & adjust checks above to support more than one load type
  79701. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  79702. }
  79703. // not as fast hardware based, but will probably never need to use
  79704. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  79705. return ((val & 0xFF) << 24)
  79706. | ((val & 0xFF00) << 8)
  79707. | ((val >> 8) & 0xFF00)
  79708. | ((val >> 24) & 0xFF);
  79709. };
  79710. /**
  79711. * It is assumed that the texture has already been created & is currently bound
  79712. */
  79713. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  79714. switch (this.loadType) {
  79715. case KhronosTextureContainer.COMPRESSED_2D:
  79716. this._upload2DCompressedLevels(gl, loadMipmaps);
  79717. break;
  79718. case KhronosTextureContainer.TEX_2D:
  79719. case KhronosTextureContainer.COMPRESSED_3D:
  79720. case KhronosTextureContainer.TEX_3D:
  79721. }
  79722. };
  79723. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  79724. // initialize width & height for level 1
  79725. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  79726. var width = this.pixelWidth;
  79727. var height = this.pixelHeight;
  79728. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  79729. for (var level = 0; level < mipmapCount; level++) {
  79730. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  79731. for (var face = 0; face < this.numberOfFaces; face++) {
  79732. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  79733. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  79734. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  79735. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  79736. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  79737. }
  79738. width = Math.max(1.0, width * 0.5);
  79739. height = Math.max(1.0, height * 0.5);
  79740. }
  79741. };
  79742. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  79743. // load types
  79744. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  79745. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  79746. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  79747. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  79748. return KhronosTextureContainer;
  79749. }());
  79750. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  79751. })(BABYLON || (BABYLON = {}));
  79752. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  79753. var BABYLON;
  79754. (function (BABYLON) {
  79755. var Debug = /** @class */ (function () {
  79756. function Debug() {
  79757. }
  79758. Debug.AxesViewer = /** @class */ (function () {
  79759. function AxesViewer(scene, scaleLines) {
  79760. if (scaleLines === void 0) { scaleLines = 1; }
  79761. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79762. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79763. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79764. this.scaleLines = 1;
  79765. this.scaleLines = scaleLines;
  79766. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  79767. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  79768. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  79769. this._xmesh.renderingGroupId = 2;
  79770. this._ymesh.renderingGroupId = 2;
  79771. this._zmesh.renderingGroupId = 2;
  79772. this._xmesh.material.checkReadyOnlyOnce = true;
  79773. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  79774. this._ymesh.material.checkReadyOnlyOnce = true;
  79775. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  79776. this._zmesh.material.checkReadyOnlyOnce = true;
  79777. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  79778. this.scene = scene;
  79779. }
  79780. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  79781. var scaleLines = this.scaleLines;
  79782. if (this._xmesh) {
  79783. this._xmesh.position.copyFrom(position);
  79784. }
  79785. if (this._ymesh) {
  79786. this._ymesh.position.copyFrom(position);
  79787. }
  79788. if (this._zmesh) {
  79789. this._zmesh.position.copyFrom(position);
  79790. }
  79791. var point2 = this._xline[1];
  79792. point2.x = xaxis.x * scaleLines;
  79793. point2.y = xaxis.y * scaleLines;
  79794. point2.z = xaxis.z * scaleLines;
  79795. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  79796. point2 = this._yline[1];
  79797. point2.x = yaxis.x * scaleLines;
  79798. point2.y = yaxis.y * scaleLines;
  79799. point2.z = yaxis.z * scaleLines;
  79800. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  79801. point2 = this._zline[1];
  79802. point2.x = zaxis.x * scaleLines;
  79803. point2.y = zaxis.y * scaleLines;
  79804. point2.z = zaxis.z * scaleLines;
  79805. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  79806. };
  79807. AxesViewer.prototype.dispose = function () {
  79808. if (this._xmesh) {
  79809. this._xmesh.dispose();
  79810. }
  79811. if (this._ymesh) {
  79812. this._ymesh.dispose();
  79813. }
  79814. if (this._zmesh) {
  79815. this._zmesh.dispose();
  79816. }
  79817. this._xmesh = null;
  79818. this._ymesh = null;
  79819. this._zmesh = null;
  79820. this.scene = null;
  79821. };
  79822. return AxesViewer;
  79823. }());
  79824. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  79825. __extends(BoneAxesViewer, _super);
  79826. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  79827. if (scaleLines === void 0) { scaleLines = 1; }
  79828. var _this = _super.call(this, scene, scaleLines) || this;
  79829. _this.pos = BABYLON.Vector3.Zero();
  79830. _this.xaxis = BABYLON.Vector3.Zero();
  79831. _this.yaxis = BABYLON.Vector3.Zero();
  79832. _this.zaxis = BABYLON.Vector3.Zero();
  79833. _this.mesh = mesh;
  79834. _this.bone = bone;
  79835. return _this;
  79836. }
  79837. BoneAxesViewer.prototype.update = function () {
  79838. if (!this.mesh || !this.bone) {
  79839. return;
  79840. }
  79841. var bone = this.bone;
  79842. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  79843. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  79844. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  79845. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  79846. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  79847. };
  79848. BoneAxesViewer.prototype.dispose = function () {
  79849. if (this.mesh) {
  79850. this.mesh = null;
  79851. this.bone = null;
  79852. _super.prototype.dispose.call(this);
  79853. }
  79854. };
  79855. return BoneAxesViewer;
  79856. }(Debug.AxesViewer));
  79857. Debug.PhysicsViewer = /** @class */ (function () {
  79858. function PhysicsViewer(scene) {
  79859. this._impostors = [];
  79860. this._meshes = [];
  79861. this._numMeshes = 0;
  79862. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79863. var physicEngine = this._scene.getPhysicsEngine();
  79864. if (physicEngine) {
  79865. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  79866. }
  79867. }
  79868. PhysicsViewer.prototype._updateDebugMeshes = function () {
  79869. var plugin = this._physicsEnginePlugin;
  79870. for (var i = 0; i < this._numMeshes; i++) {
  79871. var impostor = this._impostors[i];
  79872. if (!impostor) {
  79873. continue;
  79874. }
  79875. if (impostor.isDisposed) {
  79876. this.hideImpostor(this._impostors[i--]);
  79877. }
  79878. else {
  79879. var mesh = this._meshes[i];
  79880. if (mesh && plugin) {
  79881. plugin.syncMeshWithImpostor(mesh, impostor);
  79882. }
  79883. }
  79884. }
  79885. };
  79886. PhysicsViewer.prototype.showImpostor = function (impostor) {
  79887. if (!this._scene) {
  79888. return;
  79889. }
  79890. for (var i = 0; i < this._numMeshes; i++) {
  79891. if (this._impostors[i] == impostor) {
  79892. return;
  79893. }
  79894. }
  79895. var debugMesh = this._getDebugMesh(impostor, this._scene);
  79896. if (debugMesh) {
  79897. this._impostors[this._numMeshes] = impostor;
  79898. this._meshes[this._numMeshes] = debugMesh;
  79899. if (this._numMeshes === 0) {
  79900. this._renderFunction = this._updateDebugMeshes.bind(this);
  79901. this._scene.registerBeforeRender(this._renderFunction);
  79902. }
  79903. this._numMeshes++;
  79904. }
  79905. };
  79906. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  79907. if (!impostor || !this._scene) {
  79908. return;
  79909. }
  79910. var removed = false;
  79911. for (var i = 0; i < this._numMeshes; i++) {
  79912. if (this._impostors[i] == impostor) {
  79913. var mesh = this._meshes[i];
  79914. if (!mesh) {
  79915. continue;
  79916. }
  79917. this._scene.removeMesh(mesh);
  79918. mesh.dispose();
  79919. this._numMeshes--;
  79920. if (this._numMeshes > 0) {
  79921. this._meshes[i] = this._meshes[this._numMeshes];
  79922. this._impostors[i] = this._impostors[this._numMeshes];
  79923. this._meshes[this._numMeshes] = null;
  79924. this._impostors[this._numMeshes] = null;
  79925. }
  79926. else {
  79927. this._meshes[0] = null;
  79928. this._impostors[0] = null;
  79929. }
  79930. removed = true;
  79931. break;
  79932. }
  79933. }
  79934. if (removed && this._numMeshes === 0) {
  79935. this._scene.unregisterBeforeRender(this._renderFunction);
  79936. }
  79937. };
  79938. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  79939. if (!this._debugMaterial) {
  79940. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  79941. this._debugMaterial.wireframe = true;
  79942. }
  79943. return this._debugMaterial;
  79944. };
  79945. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  79946. if (!this._debugBoxMesh) {
  79947. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  79948. this._debugBoxMesh.renderingGroupId = 1;
  79949. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  79950. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  79951. scene.removeMesh(this._debugBoxMesh);
  79952. }
  79953. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  79954. };
  79955. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  79956. if (!this._debugSphereMesh) {
  79957. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  79958. this._debugSphereMesh.renderingGroupId = 1;
  79959. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  79960. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  79961. scene.removeMesh(this._debugSphereMesh);
  79962. }
  79963. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  79964. };
  79965. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  79966. var mesh = null;
  79967. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  79968. mesh = this._getDebugBoxMesh(scene);
  79969. impostor.getBoxSizeToRef(mesh.scaling);
  79970. }
  79971. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  79972. mesh = this._getDebugSphereMesh(scene);
  79973. var radius = impostor.getRadius();
  79974. mesh.scaling.x = radius * 2;
  79975. mesh.scaling.y = radius * 2;
  79976. mesh.scaling.z = radius * 2;
  79977. }
  79978. return mesh;
  79979. };
  79980. PhysicsViewer.prototype.dispose = function () {
  79981. for (var i = 0; i < this._numMeshes; i++) {
  79982. this.hideImpostor(this._impostors[i]);
  79983. }
  79984. if (this._debugBoxMesh) {
  79985. this._debugBoxMesh.dispose();
  79986. }
  79987. if (this._debugSphereMesh) {
  79988. this._debugSphereMesh.dispose();
  79989. }
  79990. if (this._debugMaterial) {
  79991. this._debugMaterial.dispose();
  79992. }
  79993. this._impostors.length = 0;
  79994. this._scene = null;
  79995. this._physicsEnginePlugin = null;
  79996. };
  79997. return PhysicsViewer;
  79998. }());
  79999. Debug.SkeletonViewer = /** @class */ (function () {
  80000. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  80001. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  80002. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  80003. this.skeleton = skeleton;
  80004. this.mesh = mesh;
  80005. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  80006. this.renderingGroupId = renderingGroupId;
  80007. this.color = BABYLON.Color3.White();
  80008. this._debugLines = new Array();
  80009. this._isEnabled = false;
  80010. this._scene = scene;
  80011. this.update();
  80012. this._renderFunction = this.update.bind(this);
  80013. }
  80014. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  80015. get: function () {
  80016. return this._isEnabled;
  80017. },
  80018. set: function (value) {
  80019. if (this._isEnabled === value) {
  80020. return;
  80021. }
  80022. this._isEnabled = value;
  80023. if (value) {
  80024. this._scene.registerBeforeRender(this._renderFunction);
  80025. }
  80026. else {
  80027. this._scene.unregisterBeforeRender(this._renderFunction);
  80028. }
  80029. },
  80030. enumerable: true,
  80031. configurable: true
  80032. });
  80033. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  80034. if (x === void 0) { x = 0; }
  80035. if (y === void 0) { y = 0; }
  80036. if (z === void 0) { z = 0; }
  80037. var tmat = BABYLON.Tmp.Matrix[0];
  80038. var parentBone = bone.getParent();
  80039. tmat.copyFrom(bone.getLocalMatrix());
  80040. if (x !== 0 || y !== 0 || z !== 0) {
  80041. var tmat2 = BABYLON.Tmp.Matrix[1];
  80042. BABYLON.Matrix.IdentityToRef(tmat2);
  80043. tmat2.m[12] = x;
  80044. tmat2.m[13] = y;
  80045. tmat2.m[14] = z;
  80046. tmat2.multiplyToRef(tmat, tmat);
  80047. }
  80048. if (parentBone) {
  80049. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  80050. }
  80051. tmat.multiplyToRef(meshMat, tmat);
  80052. position.x = tmat.m[12];
  80053. position.y = tmat.m[13];
  80054. position.z = tmat.m[14];
  80055. };
  80056. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  80057. var len = bones.length;
  80058. var meshPos = this.mesh.position;
  80059. for (var i = 0; i < len; i++) {
  80060. var bone = bones[i];
  80061. var points = this._debugLines[i];
  80062. if (!points) {
  80063. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80064. this._debugLines[i] = points;
  80065. }
  80066. this._getBonePosition(points[0], bone, meshMat);
  80067. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  80068. points[0].subtractInPlace(meshPos);
  80069. points[1].subtractInPlace(meshPos);
  80070. }
  80071. };
  80072. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  80073. var len = bones.length;
  80074. var boneNum = 0;
  80075. var meshPos = this.mesh.position;
  80076. for (var i = len - 1; i >= 0; i--) {
  80077. var childBone = bones[i];
  80078. var parentBone = childBone.getParent();
  80079. if (!parentBone) {
  80080. continue;
  80081. }
  80082. var points = this._debugLines[boneNum];
  80083. if (!points) {
  80084. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80085. this._debugLines[boneNum] = points;
  80086. }
  80087. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  80088. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  80089. points[0].subtractInPlace(meshPos);
  80090. points[1].subtractInPlace(meshPos);
  80091. boneNum++;
  80092. }
  80093. };
  80094. SkeletonViewer.prototype.update = function () {
  80095. if (this.autoUpdateBonesMatrices) {
  80096. this.skeleton.computeAbsoluteTransforms();
  80097. }
  80098. if (this.skeleton.bones[0].length === undefined) {
  80099. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  80100. }
  80101. else {
  80102. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  80103. }
  80104. if (!this._debugMesh) {
  80105. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  80106. this._debugMesh.renderingGroupId = this.renderingGroupId;
  80107. }
  80108. else {
  80109. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  80110. }
  80111. this._debugMesh.position.copyFrom(this.mesh.position);
  80112. this._debugMesh.color = this.color;
  80113. };
  80114. SkeletonViewer.prototype.dispose = function () {
  80115. if (this._debugMesh) {
  80116. this.isEnabled = false;
  80117. this._debugMesh.dispose();
  80118. this._debugMesh = null;
  80119. }
  80120. };
  80121. return SkeletonViewer;
  80122. }());
  80123. return Debug;
  80124. }());
  80125. BABYLON.Debug = Debug;
  80126. })(BABYLON || (BABYLON = {}));
  80127. //# sourceMappingURL=babylon.debugModules.js.map
  80128. var BABYLON;
  80129. (function (BABYLON) {
  80130. var RayHelper = /** @class */ (function () {
  80131. function RayHelper(ray) {
  80132. this.ray = ray;
  80133. }
  80134. RayHelper.CreateAndShow = function (ray, scene, color) {
  80135. var helper = new RayHelper(ray);
  80136. helper.show(scene, color);
  80137. return helper;
  80138. };
  80139. RayHelper.prototype.show = function (scene, color) {
  80140. if (!this._renderFunction && this.ray) {
  80141. var ray = this.ray;
  80142. this._renderFunction = this._render.bind(this);
  80143. this._scene = scene;
  80144. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  80145. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  80146. if (this._renderFunction) {
  80147. this._scene.registerBeforeRender(this._renderFunction);
  80148. }
  80149. }
  80150. if (color && this._renderLine) {
  80151. this._renderLine.color.copyFrom(color);
  80152. }
  80153. };
  80154. RayHelper.prototype.hide = function () {
  80155. if (this._renderFunction && this._scene) {
  80156. this._scene.unregisterBeforeRender(this._renderFunction);
  80157. this._scene = null;
  80158. this._renderFunction = null;
  80159. if (this._renderLine) {
  80160. this._renderLine.dispose();
  80161. this._renderLine = null;
  80162. }
  80163. this._renderPoints = [];
  80164. }
  80165. };
  80166. RayHelper.prototype._render = function () {
  80167. var ray = this.ray;
  80168. if (!ray) {
  80169. return;
  80170. }
  80171. var point = this._renderPoints[1];
  80172. var len = Math.min(ray.length, 1000000);
  80173. point.copyFrom(ray.direction);
  80174. point.scaleInPlace(len);
  80175. point.addInPlace(ray.origin);
  80176. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  80177. };
  80178. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  80179. this._attachedToMesh = mesh;
  80180. var ray = this.ray;
  80181. if (!ray) {
  80182. return;
  80183. }
  80184. if (!ray.direction) {
  80185. ray.direction = BABYLON.Vector3.Zero();
  80186. }
  80187. if (!ray.origin) {
  80188. ray.origin = BABYLON.Vector3.Zero();
  80189. }
  80190. if (length) {
  80191. ray.length = length;
  80192. }
  80193. if (!meshSpaceOrigin) {
  80194. meshSpaceOrigin = BABYLON.Vector3.Zero();
  80195. }
  80196. if (!meshSpaceDirection) {
  80197. // -1 so that this will work with Mesh.lookAt
  80198. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  80199. }
  80200. if (!this._meshSpaceDirection) {
  80201. this._meshSpaceDirection = meshSpaceDirection.clone();
  80202. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  80203. }
  80204. else {
  80205. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  80206. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  80207. }
  80208. if (!this._updateToMeshFunction) {
  80209. this._updateToMeshFunction = this._updateToMesh.bind(this);
  80210. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  80211. }
  80212. this._updateToMesh();
  80213. };
  80214. RayHelper.prototype.detachFromMesh = function () {
  80215. if (this._attachedToMesh) {
  80216. if (this._updateToMeshFunction) {
  80217. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  80218. }
  80219. this._attachedToMesh = null;
  80220. this._updateToMeshFunction = null;
  80221. }
  80222. };
  80223. RayHelper.prototype._updateToMesh = function () {
  80224. var ray = this.ray;
  80225. if (!this._attachedToMesh || !ray) {
  80226. return;
  80227. }
  80228. if (this._attachedToMesh._isDisposed) {
  80229. this.detachFromMesh();
  80230. return;
  80231. }
  80232. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  80233. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  80234. };
  80235. RayHelper.prototype.dispose = function () {
  80236. this.hide();
  80237. this.detachFromMesh();
  80238. this.ray = null;
  80239. };
  80240. return RayHelper;
  80241. }());
  80242. BABYLON.RayHelper = RayHelper;
  80243. })(BABYLON || (BABYLON = {}));
  80244. //# sourceMappingURL=babylon.rayHelper.js.map
  80245. var BABYLON;
  80246. (function (BABYLON) {
  80247. // load the inspector using require, if not present in the global namespace.
  80248. var DebugLayer = /** @class */ (function () {
  80249. function DebugLayer(scene) {
  80250. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  80251. this._scene = scene;
  80252. // load inspector using require, if it doesn't exist on the global namespace.
  80253. }
  80254. /** Creates the inspector window. */
  80255. DebugLayer.prototype._createInspector = function (config) {
  80256. if (config === void 0) { config = {}; }
  80257. var popup = config.popup || false;
  80258. var initialTab = config.initialTab || 0;
  80259. var parentElement = config.parentElement || null;
  80260. if (!this._inspector) {
  80261. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  80262. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  80263. } // else nothing to do,; instance is already existing
  80264. };
  80265. DebugLayer.prototype.isVisible = function () {
  80266. if (!this._inspector) {
  80267. return false;
  80268. }
  80269. return true;
  80270. };
  80271. DebugLayer.prototype.hide = function () {
  80272. if (this._inspector) {
  80273. try {
  80274. this._inspector.dispose();
  80275. }
  80276. catch (e) {
  80277. // If the inspector has been removed directly from the inspector tool
  80278. }
  80279. this._inspector = null;
  80280. }
  80281. };
  80282. DebugLayer.prototype.show = function (config) {
  80283. if (config === void 0) { config = {}; }
  80284. if (typeof this.BJSINSPECTOR == 'undefined') {
  80285. // Load inspector and add it to the DOM
  80286. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  80287. }
  80288. else {
  80289. // Otherwise creates the inspector
  80290. this._createInspector(config);
  80291. }
  80292. };
  80293. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  80294. return DebugLayer;
  80295. }());
  80296. BABYLON.DebugLayer = DebugLayer;
  80297. })(BABYLON || (BABYLON = {}));
  80298. //# sourceMappingURL=babylon.debugLayer.js.map
  80299. var BABYLON;
  80300. (function (BABYLON) {
  80301. var BoundingBoxRenderer = /** @class */ (function () {
  80302. function BoundingBoxRenderer(scene) {
  80303. this.frontColor = new BABYLON.Color3(1, 1, 1);
  80304. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  80305. this.showBackLines = true;
  80306. this.renderList = new BABYLON.SmartArray(32);
  80307. this._vertexBuffers = {};
  80308. this._scene = scene;
  80309. }
  80310. BoundingBoxRenderer.prototype._prepareRessources = function () {
  80311. if (this._colorShader) {
  80312. return;
  80313. }
  80314. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  80315. attributes: [BABYLON.VertexBuffer.PositionKind],
  80316. uniforms: ["world", "viewProjection", "color"]
  80317. });
  80318. var engine = this._scene.getEngine();
  80319. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  80320. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  80321. this._createIndexBuffer();
  80322. };
  80323. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  80324. var engine = this._scene.getEngine();
  80325. 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]);
  80326. };
  80327. BoundingBoxRenderer.prototype._rebuild = function () {
  80328. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80329. if (vb) {
  80330. vb._rebuild();
  80331. }
  80332. this._createIndexBuffer();
  80333. };
  80334. BoundingBoxRenderer.prototype.reset = function () {
  80335. this.renderList.reset();
  80336. };
  80337. BoundingBoxRenderer.prototype.render = function () {
  80338. if (this.renderList.length === 0) {
  80339. return;
  80340. }
  80341. this._prepareRessources();
  80342. if (!this._colorShader.isReady()) {
  80343. return;
  80344. }
  80345. var engine = this._scene.getEngine();
  80346. engine.setDepthWrite(false);
  80347. this._colorShader._preBind();
  80348. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  80349. var boundingBox = this.renderList.data[boundingBoxIndex];
  80350. var min = boundingBox.minimum;
  80351. var max = boundingBox.maximum;
  80352. var diff = max.subtract(min);
  80353. var median = min.add(diff.scale(0.5));
  80354. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  80355. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  80356. .multiply(boundingBox.getWorldMatrix());
  80357. // VBOs
  80358. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  80359. if (this.showBackLines) {
  80360. // Back
  80361. engine.setDepthFunctionToGreaterOrEqual();
  80362. this._scene.resetCachedMaterial();
  80363. this._colorShader.setColor4("color", this.backColor.toColor4());
  80364. this._colorShader.bind(worldMatrix);
  80365. // Draw order
  80366. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  80367. }
  80368. // Front
  80369. engine.setDepthFunctionToLess();
  80370. this._scene.resetCachedMaterial();
  80371. this._colorShader.setColor4("color", this.frontColor.toColor4());
  80372. this._colorShader.bind(worldMatrix);
  80373. // Draw order
  80374. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  80375. }
  80376. this._colorShader.unbind();
  80377. engine.setDepthFunctionToLessOrEqual();
  80378. engine.setDepthWrite(true);
  80379. };
  80380. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  80381. this._prepareRessources();
  80382. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  80383. return;
  80384. }
  80385. var engine = this._scene.getEngine();
  80386. engine.setDepthWrite(false);
  80387. engine.setColorWrite(false);
  80388. this._colorShader._preBind();
  80389. var boundingBox = mesh._boundingInfo.boundingBox;
  80390. var min = boundingBox.minimum;
  80391. var max = boundingBox.maximum;
  80392. var diff = max.subtract(min);
  80393. var median = min.add(diff.scale(0.5));
  80394. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  80395. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  80396. .multiply(boundingBox.getWorldMatrix());
  80397. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  80398. engine.setDepthFunctionToLess();
  80399. this._scene.resetCachedMaterial();
  80400. this._colorShader.bind(worldMatrix);
  80401. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  80402. this._colorShader.unbind();
  80403. engine.setDepthFunctionToLessOrEqual();
  80404. engine.setDepthWrite(true);
  80405. engine.setColorWrite(true);
  80406. };
  80407. BoundingBoxRenderer.prototype.dispose = function () {
  80408. if (!this._colorShader) {
  80409. return;
  80410. }
  80411. this.renderList.dispose();
  80412. this._colorShader.dispose();
  80413. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80414. if (buffer) {
  80415. buffer.dispose();
  80416. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  80417. }
  80418. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  80419. };
  80420. return BoundingBoxRenderer;
  80421. }());
  80422. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  80423. })(BABYLON || (BABYLON = {}));
  80424. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  80425. var BABYLON;
  80426. (function (BABYLON) {
  80427. var MorphTarget = /** @class */ (function () {
  80428. function MorphTarget(name, influence) {
  80429. if (influence === void 0) { influence = 0; }
  80430. this.name = name;
  80431. this.animations = new Array();
  80432. this._positions = null;
  80433. this._normals = null;
  80434. this._tangents = null;
  80435. this.onInfluenceChanged = new BABYLON.Observable();
  80436. this.influence = influence;
  80437. }
  80438. Object.defineProperty(MorphTarget.prototype, "influence", {
  80439. get: function () {
  80440. return this._influence;
  80441. },
  80442. set: function (influence) {
  80443. if (this._influence === influence) {
  80444. return;
  80445. }
  80446. var previous = this._influence;
  80447. this._influence = influence;
  80448. if (this.onInfluenceChanged.hasObservers) {
  80449. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  80450. }
  80451. },
  80452. enumerable: true,
  80453. configurable: true
  80454. });
  80455. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  80456. get: function () {
  80457. return !!this._positions;
  80458. },
  80459. enumerable: true,
  80460. configurable: true
  80461. });
  80462. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  80463. get: function () {
  80464. return !!this._normals;
  80465. },
  80466. enumerable: true,
  80467. configurable: true
  80468. });
  80469. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  80470. get: function () {
  80471. return !!this._tangents;
  80472. },
  80473. enumerable: true,
  80474. configurable: true
  80475. });
  80476. MorphTarget.prototype.setPositions = function (data) {
  80477. this._positions = data;
  80478. };
  80479. MorphTarget.prototype.getPositions = function () {
  80480. return this._positions;
  80481. };
  80482. MorphTarget.prototype.setNormals = function (data) {
  80483. this._normals = data;
  80484. };
  80485. MorphTarget.prototype.getNormals = function () {
  80486. return this._normals;
  80487. };
  80488. MorphTarget.prototype.setTangents = function (data) {
  80489. this._tangents = data;
  80490. };
  80491. MorphTarget.prototype.getTangents = function () {
  80492. return this._tangents;
  80493. };
  80494. /**
  80495. * Serializes the current target into a Serialization object.
  80496. * Returns the serialized object.
  80497. */
  80498. MorphTarget.prototype.serialize = function () {
  80499. var serializationObject = {};
  80500. serializationObject.name = this.name;
  80501. serializationObject.influence = this.influence;
  80502. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  80503. if (this.hasNormals) {
  80504. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  80505. }
  80506. if (this.hasTangents) {
  80507. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  80508. }
  80509. // Animations
  80510. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  80511. return serializationObject;
  80512. };
  80513. // Statics
  80514. MorphTarget.Parse = function (serializationObject) {
  80515. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  80516. result.setPositions(serializationObject.positions);
  80517. if (serializationObject.normals) {
  80518. result.setNormals(serializationObject.normals);
  80519. }
  80520. if (serializationObject.tangents) {
  80521. result.setTangents(serializationObject.tangents);
  80522. }
  80523. // Animations
  80524. if (serializationObject.animations) {
  80525. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  80526. var parsedAnimation = serializationObject.animations[animationIndex];
  80527. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  80528. }
  80529. }
  80530. return result;
  80531. };
  80532. MorphTarget.FromMesh = function (mesh, name, influence) {
  80533. if (!name) {
  80534. name = mesh.name;
  80535. }
  80536. var result = new MorphTarget(name, influence);
  80537. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  80538. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  80539. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  80540. }
  80541. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  80542. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  80543. }
  80544. return result;
  80545. };
  80546. return MorphTarget;
  80547. }());
  80548. BABYLON.MorphTarget = MorphTarget;
  80549. })(BABYLON || (BABYLON = {}));
  80550. //# sourceMappingURL=babylon.morphTarget.js.map
  80551. var BABYLON;
  80552. (function (BABYLON) {
  80553. var MorphTargetManager = /** @class */ (function () {
  80554. function MorphTargetManager(scene) {
  80555. if (scene === void 0) { scene = null; }
  80556. this._targets = new Array();
  80557. this._targetObservable = new Array();
  80558. this._activeTargets = new BABYLON.SmartArray(16);
  80559. this._supportsNormals = false;
  80560. this._supportsTangents = false;
  80561. this._vertexCount = 0;
  80562. this._uniqueId = 0;
  80563. this._tempInfluences = new Array();
  80564. if (!scene) {
  80565. scene = BABYLON.Engine.LastCreatedScene;
  80566. }
  80567. this._scene = scene;
  80568. if (this._scene) {
  80569. this._scene.morphTargetManagers.push(this);
  80570. this._uniqueId = this._scene.getUniqueId();
  80571. }
  80572. }
  80573. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  80574. get: function () {
  80575. return this._uniqueId;
  80576. },
  80577. enumerable: true,
  80578. configurable: true
  80579. });
  80580. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  80581. get: function () {
  80582. return this._vertexCount;
  80583. },
  80584. enumerable: true,
  80585. configurable: true
  80586. });
  80587. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  80588. get: function () {
  80589. return this._supportsNormals;
  80590. },
  80591. enumerable: true,
  80592. configurable: true
  80593. });
  80594. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  80595. get: function () {
  80596. return this._supportsTangents;
  80597. },
  80598. enumerable: true,
  80599. configurable: true
  80600. });
  80601. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  80602. get: function () {
  80603. return this._targets.length;
  80604. },
  80605. enumerable: true,
  80606. configurable: true
  80607. });
  80608. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  80609. get: function () {
  80610. return this._activeTargets.length;
  80611. },
  80612. enumerable: true,
  80613. configurable: true
  80614. });
  80615. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  80616. get: function () {
  80617. return this._influences;
  80618. },
  80619. enumerable: true,
  80620. configurable: true
  80621. });
  80622. MorphTargetManager.prototype.getActiveTarget = function (index) {
  80623. return this._activeTargets.data[index];
  80624. };
  80625. MorphTargetManager.prototype.getTarget = function (index) {
  80626. return this._targets[index];
  80627. };
  80628. MorphTargetManager.prototype.addTarget = function (target) {
  80629. var _this = this;
  80630. this._targets.push(target);
  80631. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  80632. _this._syncActiveTargets(needUpdate);
  80633. }));
  80634. this._syncActiveTargets(true);
  80635. };
  80636. MorphTargetManager.prototype.removeTarget = function (target) {
  80637. var index = this._targets.indexOf(target);
  80638. if (index >= 0) {
  80639. this._targets.splice(index, 1);
  80640. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  80641. this._syncActiveTargets(true);
  80642. }
  80643. };
  80644. /**
  80645. * Serializes the current manager into a Serialization object.
  80646. * Returns the serialized object.
  80647. */
  80648. MorphTargetManager.prototype.serialize = function () {
  80649. var serializationObject = {};
  80650. serializationObject.id = this.uniqueId;
  80651. serializationObject.targets = [];
  80652. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  80653. var target = _a[_i];
  80654. serializationObject.targets.push(target.serialize());
  80655. }
  80656. return serializationObject;
  80657. };
  80658. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  80659. var influenceCount = 0;
  80660. this._activeTargets.reset();
  80661. this._supportsNormals = true;
  80662. this._supportsTangents = true;
  80663. this._vertexCount = 0;
  80664. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  80665. var target = _a[_i];
  80666. this._activeTargets.push(target);
  80667. this._tempInfluences[influenceCount++] = target.influence;
  80668. var positions = target.getPositions();
  80669. if (positions) {
  80670. this._supportsNormals = this._supportsNormals && target.hasNormals;
  80671. this._supportsTangents = this._supportsTangents && target.hasTangents;
  80672. var vertexCount = positions.length / 3;
  80673. if (this._vertexCount === 0) {
  80674. this._vertexCount = vertexCount;
  80675. }
  80676. else if (this._vertexCount !== vertexCount) {
  80677. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  80678. return;
  80679. }
  80680. }
  80681. }
  80682. if (!this._influences || this._influences.length !== influenceCount) {
  80683. this._influences = new Float32Array(influenceCount);
  80684. }
  80685. for (var index = 0; index < influenceCount; index++) {
  80686. this._influences[index] = this._tempInfluences[index];
  80687. }
  80688. if (needUpdate && this._scene) {
  80689. // Flag meshes as dirty to resync with the active targets
  80690. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  80691. var mesh = _c[_b];
  80692. if (mesh.morphTargetManager === this) {
  80693. mesh._syncGeometryWithMorphTargetManager();
  80694. }
  80695. }
  80696. }
  80697. };
  80698. // Statics
  80699. MorphTargetManager.Parse = function (serializationObject, scene) {
  80700. var result = new MorphTargetManager(scene);
  80701. result._uniqueId = serializationObject.id;
  80702. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  80703. var targetData = _a[_i];
  80704. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  80705. }
  80706. return result;
  80707. };
  80708. return MorphTargetManager;
  80709. }());
  80710. BABYLON.MorphTargetManager = MorphTargetManager;
  80711. })(BABYLON || (BABYLON = {}));
  80712. //# sourceMappingURL=babylon.morphTargetManager.js.map
  80713. var BABYLON;
  80714. (function (BABYLON) {
  80715. var Octree = /** @class */ (function () {
  80716. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  80717. if (maxDepth === void 0) { maxDepth = 2; }
  80718. this.maxDepth = maxDepth;
  80719. this.dynamicContent = new Array();
  80720. this._maxBlockCapacity = maxBlockCapacity || 64;
  80721. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  80722. this._creationFunc = creationFunc;
  80723. }
  80724. // Methods
  80725. Octree.prototype.update = function (worldMin, worldMax, entries) {
  80726. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  80727. };
  80728. Octree.prototype.addMesh = function (entry) {
  80729. for (var index = 0; index < this.blocks.length; index++) {
  80730. var block = this.blocks[index];
  80731. block.addEntry(entry);
  80732. }
  80733. };
  80734. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  80735. this._selectionContent.reset();
  80736. for (var index = 0; index < this.blocks.length; index++) {
  80737. var block = this.blocks[index];
  80738. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  80739. }
  80740. if (allowDuplicate) {
  80741. this._selectionContent.concat(this.dynamicContent);
  80742. }
  80743. else {
  80744. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  80745. }
  80746. return this._selectionContent;
  80747. };
  80748. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  80749. this._selectionContent.reset();
  80750. for (var index = 0; index < this.blocks.length; index++) {
  80751. var block = this.blocks[index];
  80752. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  80753. }
  80754. if (allowDuplicate) {
  80755. this._selectionContent.concat(this.dynamicContent);
  80756. }
  80757. else {
  80758. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  80759. }
  80760. return this._selectionContent;
  80761. };
  80762. Octree.prototype.intersectsRay = function (ray) {
  80763. this._selectionContent.reset();
  80764. for (var index = 0; index < this.blocks.length; index++) {
  80765. var block = this.blocks[index];
  80766. block.intersectsRay(ray, this._selectionContent);
  80767. }
  80768. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  80769. return this._selectionContent;
  80770. };
  80771. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  80772. target.blocks = new Array();
  80773. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  80774. // Segmenting space
  80775. for (var x = 0; x < 2; x++) {
  80776. for (var y = 0; y < 2; y++) {
  80777. for (var z = 0; z < 2; z++) {
  80778. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  80779. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  80780. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  80781. block.addEntries(entries);
  80782. target.blocks.push(block);
  80783. }
  80784. }
  80785. }
  80786. };
  80787. Octree.CreationFuncForMeshes = function (entry, block) {
  80788. var boundingInfo = entry.getBoundingInfo();
  80789. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  80790. block.entries.push(entry);
  80791. }
  80792. };
  80793. Octree.CreationFuncForSubMeshes = function (entry, block) {
  80794. var boundingInfo = entry.getBoundingInfo();
  80795. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  80796. block.entries.push(entry);
  80797. }
  80798. };
  80799. return Octree;
  80800. }());
  80801. BABYLON.Octree = Octree;
  80802. })(BABYLON || (BABYLON = {}));
  80803. //# sourceMappingURL=babylon.octree.js.map
  80804. var BABYLON;
  80805. (function (BABYLON) {
  80806. var OctreeBlock = /** @class */ (function () {
  80807. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  80808. this.entries = new Array();
  80809. this._boundingVectors = new Array();
  80810. this._capacity = capacity;
  80811. this._depth = depth;
  80812. this._maxDepth = maxDepth;
  80813. this._creationFunc = creationFunc;
  80814. this._minPoint = minPoint;
  80815. this._maxPoint = maxPoint;
  80816. this._boundingVectors.push(minPoint.clone());
  80817. this._boundingVectors.push(maxPoint.clone());
  80818. this._boundingVectors.push(minPoint.clone());
  80819. this._boundingVectors[2].x = maxPoint.x;
  80820. this._boundingVectors.push(minPoint.clone());
  80821. this._boundingVectors[3].y = maxPoint.y;
  80822. this._boundingVectors.push(minPoint.clone());
  80823. this._boundingVectors[4].z = maxPoint.z;
  80824. this._boundingVectors.push(maxPoint.clone());
  80825. this._boundingVectors[5].z = minPoint.z;
  80826. this._boundingVectors.push(maxPoint.clone());
  80827. this._boundingVectors[6].x = minPoint.x;
  80828. this._boundingVectors.push(maxPoint.clone());
  80829. this._boundingVectors[7].y = minPoint.y;
  80830. }
  80831. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  80832. // Property
  80833. get: function () {
  80834. return this._capacity;
  80835. },
  80836. enumerable: true,
  80837. configurable: true
  80838. });
  80839. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  80840. get: function () {
  80841. return this._minPoint;
  80842. },
  80843. enumerable: true,
  80844. configurable: true
  80845. });
  80846. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  80847. get: function () {
  80848. return this._maxPoint;
  80849. },
  80850. enumerable: true,
  80851. configurable: true
  80852. });
  80853. // Methods
  80854. OctreeBlock.prototype.addEntry = function (entry) {
  80855. if (this.blocks) {
  80856. for (var index = 0; index < this.blocks.length; index++) {
  80857. var block = this.blocks[index];
  80858. block.addEntry(entry);
  80859. }
  80860. return;
  80861. }
  80862. this._creationFunc(entry, this);
  80863. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  80864. this.createInnerBlocks();
  80865. }
  80866. };
  80867. OctreeBlock.prototype.addEntries = function (entries) {
  80868. for (var index = 0; index < entries.length; index++) {
  80869. var mesh = entries[index];
  80870. this.addEntry(mesh);
  80871. }
  80872. };
  80873. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  80874. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  80875. if (this.blocks) {
  80876. for (var index = 0; index < this.blocks.length; index++) {
  80877. var block = this.blocks[index];
  80878. block.select(frustumPlanes, selection, allowDuplicate);
  80879. }
  80880. return;
  80881. }
  80882. if (allowDuplicate) {
  80883. selection.concat(this.entries);
  80884. }
  80885. else {
  80886. selection.concatWithNoDuplicate(this.entries);
  80887. }
  80888. }
  80889. };
  80890. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  80891. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  80892. if (this.blocks) {
  80893. for (var index = 0; index < this.blocks.length; index++) {
  80894. var block = this.blocks[index];
  80895. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  80896. }
  80897. return;
  80898. }
  80899. if (allowDuplicate) {
  80900. selection.concat(this.entries);
  80901. }
  80902. else {
  80903. selection.concatWithNoDuplicate(this.entries);
  80904. }
  80905. }
  80906. };
  80907. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  80908. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  80909. if (this.blocks) {
  80910. for (var index = 0; index < this.blocks.length; index++) {
  80911. var block = this.blocks[index];
  80912. block.intersectsRay(ray, selection);
  80913. }
  80914. return;
  80915. }
  80916. selection.concatWithNoDuplicate(this.entries);
  80917. }
  80918. };
  80919. OctreeBlock.prototype.createInnerBlocks = function () {
  80920. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  80921. };
  80922. return OctreeBlock;
  80923. }());
  80924. BABYLON.OctreeBlock = OctreeBlock;
  80925. })(BABYLON || (BABYLON = {}));
  80926. //# sourceMappingURL=babylon.octreeBlock.js.map
  80927. var BABYLON;
  80928. (function (BABYLON) {
  80929. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  80930. __extends(VRDistortionCorrectionPostProcess, _super);
  80931. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  80932. var _this = _super.call(this, name, "vrDistortionCorrection", [
  80933. 'LensCenter',
  80934. 'Scale',
  80935. 'ScaleIn',
  80936. 'HmdWarpParam'
  80937. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  80938. _this._isRightEye = isRightEye;
  80939. _this._distortionFactors = vrMetrics.distortionK;
  80940. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  80941. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  80942. _this.adaptScaleToCurrentViewport = true;
  80943. _this.onSizeChangedObservable.add(function () {
  80944. _this.aspectRatio = _this.width * .5 / _this.height;
  80945. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  80946. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  80947. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  80948. });
  80949. _this.onApplyObservable.add(function (effect) {
  80950. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  80951. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  80952. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  80953. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  80954. });
  80955. return _this;
  80956. }
  80957. return VRDistortionCorrectionPostProcess;
  80958. }(BABYLON.PostProcess));
  80959. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  80960. })(BABYLON || (BABYLON = {}));
  80961. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  80962. var BABYLON;
  80963. (function (BABYLON) {
  80964. var AnaglyphPostProcess = /** @class */ (function (_super) {
  80965. __extends(AnaglyphPostProcess, _super);
  80966. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  80967. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  80968. _this._passedProcess = rigCameras[0]._rigPostProcess;
  80969. _this.onApplyObservable.add(function (effect) {
  80970. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  80971. });
  80972. return _this;
  80973. }
  80974. return AnaglyphPostProcess;
  80975. }(BABYLON.PostProcess));
  80976. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  80977. })(BABYLON || (BABYLON = {}));
  80978. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  80979. var BABYLON;
  80980. (function (BABYLON) {
  80981. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  80982. __extends(StereoscopicInterlacePostProcess, _super);
  80983. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  80984. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  80985. _this._passedProcess = rigCameras[0]._rigPostProcess;
  80986. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  80987. _this.onSizeChangedObservable.add(function () {
  80988. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  80989. });
  80990. _this.onApplyObservable.add(function (effect) {
  80991. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  80992. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  80993. });
  80994. return _this;
  80995. }
  80996. return StereoscopicInterlacePostProcess;
  80997. }(BABYLON.PostProcess));
  80998. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  80999. })(BABYLON || (BABYLON = {}));
  81000. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  81001. var BABYLON;
  81002. (function (BABYLON) {
  81003. /**
  81004. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  81005. * Screen rotation is taken into account.
  81006. */
  81007. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  81008. function FreeCameraDeviceOrientationInput() {
  81009. var _this = this;
  81010. this._screenOrientationAngle = 0;
  81011. this._screenQuaternion = new BABYLON.Quaternion();
  81012. this._alpha = 0;
  81013. this._beta = 0;
  81014. this._gamma = 0;
  81015. this._orientationChanged = function () {
  81016. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  81017. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  81018. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  81019. };
  81020. this._deviceOrientation = function (evt) {
  81021. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  81022. _this._beta = evt.beta !== null ? evt.beta : 0;
  81023. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  81024. };
  81025. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  81026. this._orientationChanged();
  81027. }
  81028. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  81029. get: function () {
  81030. return this._camera;
  81031. },
  81032. set: function (camera) {
  81033. this._camera = camera;
  81034. if (this._camera != null && !this._camera.rotationQuaternion) {
  81035. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  81036. }
  81037. },
  81038. enumerable: true,
  81039. configurable: true
  81040. });
  81041. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  81042. window.addEventListener("orientationchange", this._orientationChanged);
  81043. window.addEventListener("deviceorientation", this._deviceOrientation);
  81044. //In certain cases, the attach control is called AFTER orientation was changed,
  81045. //So this is needed.
  81046. this._orientationChanged();
  81047. };
  81048. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  81049. window.removeEventListener("orientationchange", this._orientationChanged);
  81050. window.removeEventListener("deviceorientation", this._deviceOrientation);
  81051. };
  81052. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  81053. //if no device orientation provided, don't update the rotation.
  81054. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  81055. if (!this._alpha)
  81056. return;
  81057. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  81058. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  81059. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  81060. //Mirror on XY Plane
  81061. this._camera.rotationQuaternion.z *= -1;
  81062. this._camera.rotationQuaternion.w *= -1;
  81063. };
  81064. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  81065. return "FreeCameraDeviceOrientationInput";
  81066. };
  81067. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  81068. return "deviceOrientation";
  81069. };
  81070. return FreeCameraDeviceOrientationInput;
  81071. }());
  81072. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  81073. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  81074. })(BABYLON || (BABYLON = {}));
  81075. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  81076. var BABYLON;
  81077. (function (BABYLON) {
  81078. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  81079. function ArcRotateCameraVRDeviceOrientationInput() {
  81080. this.alphaCorrection = 1;
  81081. this.betaCorrection = 1;
  81082. this.gammaCorrection = 1;
  81083. this._alpha = 0;
  81084. this._gamma = 0;
  81085. this._dirty = false;
  81086. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  81087. }
  81088. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  81089. this.camera.attachControl(element, noPreventDefault);
  81090. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  81091. };
  81092. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  81093. if (evt.alpha !== null) {
  81094. this._alpha = +evt.alpha | 0;
  81095. }
  81096. if (evt.gamma !== null) {
  81097. this._gamma = +evt.gamma | 0;
  81098. }
  81099. this._dirty = true;
  81100. };
  81101. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  81102. if (this._dirty) {
  81103. this._dirty = false;
  81104. if (this._gamma < 0) {
  81105. this._gamma = 180 + this._gamma;
  81106. }
  81107. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  81108. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  81109. }
  81110. };
  81111. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  81112. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  81113. };
  81114. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  81115. return "ArcRotateCameraVRDeviceOrientationInput";
  81116. };
  81117. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  81118. return "VRDeviceOrientation";
  81119. };
  81120. return ArcRotateCameraVRDeviceOrientationInput;
  81121. }());
  81122. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  81123. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  81124. })(BABYLON || (BABYLON = {}));
  81125. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  81126. var BABYLON;
  81127. (function (BABYLON) {
  81128. var VRCameraMetrics = /** @class */ (function () {
  81129. function VRCameraMetrics() {
  81130. this.compensateDistortion = true;
  81131. }
  81132. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  81133. get: function () {
  81134. return this.hResolution / (2 * this.vResolution);
  81135. },
  81136. enumerable: true,
  81137. configurable: true
  81138. });
  81139. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  81140. get: function () {
  81141. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  81142. },
  81143. enumerable: true,
  81144. configurable: true
  81145. });
  81146. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  81147. get: function () {
  81148. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  81149. var h = (4 * meters) / this.hScreenSize;
  81150. return BABYLON.Matrix.Translation(h, 0, 0);
  81151. },
  81152. enumerable: true,
  81153. configurable: true
  81154. });
  81155. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  81156. get: function () {
  81157. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  81158. var h = (4 * meters) / this.hScreenSize;
  81159. return BABYLON.Matrix.Translation(-h, 0, 0);
  81160. },
  81161. enumerable: true,
  81162. configurable: true
  81163. });
  81164. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  81165. get: function () {
  81166. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  81167. },
  81168. enumerable: true,
  81169. configurable: true
  81170. });
  81171. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  81172. get: function () {
  81173. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  81174. },
  81175. enumerable: true,
  81176. configurable: true
  81177. });
  81178. VRCameraMetrics.GetDefault = function () {
  81179. var result = new VRCameraMetrics();
  81180. result.hResolution = 1280;
  81181. result.vResolution = 800;
  81182. result.hScreenSize = 0.149759993;
  81183. result.vScreenSize = 0.0935999975;
  81184. result.vScreenCenter = 0.0467999987;
  81185. result.eyeToScreenDistance = 0.0410000011;
  81186. result.lensSeparationDistance = 0.0635000020;
  81187. result.interpupillaryDistance = 0.0640000030;
  81188. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  81189. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  81190. result.postProcessScaleFactor = 1.714605507808412;
  81191. result.lensCenterOffset = 0.151976421;
  81192. return result;
  81193. };
  81194. return VRCameraMetrics;
  81195. }());
  81196. BABYLON.VRCameraMetrics = VRCameraMetrics;
  81197. })(BABYLON || (BABYLON = {}));
  81198. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  81199. var BABYLON;
  81200. (function (BABYLON) {
  81201. /**
  81202. * This represents a WebVR camera.
  81203. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  81204. * @example http://doc.babylonjs.com/how_to/webvr_camera
  81205. */
  81206. var WebVRFreeCamera = /** @class */ (function (_super) {
  81207. __extends(WebVRFreeCamera, _super);
  81208. /**
  81209. * Instantiates a WebVRFreeCamera.
  81210. * @param name The name of the WebVRFreeCamera
  81211. * @param position The starting anchor position for the camera
  81212. * @param scene The scene the camera belongs to
  81213. * @param webVROptions a set of customizable options for the webVRCamera
  81214. */
  81215. function WebVRFreeCamera(name, position, scene, webVROptions) {
  81216. if (webVROptions === void 0) { webVROptions = {}; }
  81217. var _this = _super.call(this, name, position, scene) || this;
  81218. _this.webVROptions = webVROptions;
  81219. /**
  81220. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  81221. */
  81222. _this._vrDevice = null;
  81223. /**
  81224. * The rawPose of the vrDevice.
  81225. */
  81226. _this.rawPose = null;
  81227. _this._specsVersion = "1.1";
  81228. _this._attached = false;
  81229. _this._descendants = [];
  81230. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  81231. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  81232. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  81233. _this._standingMatrix = null;
  81234. /**
  81235. * Represents device position in babylon space.
  81236. */
  81237. _this.devicePosition = BABYLON.Vector3.Zero();
  81238. /**
  81239. * Represents device rotation in babylon space.
  81240. */
  81241. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  81242. /**
  81243. * The scale of the device to be used when translating from device space to babylon space.
  81244. */
  81245. _this.deviceScaleFactor = 1;
  81246. _this._deviceToWorld = BABYLON.Matrix.Identity();
  81247. _this._worldToDevice = BABYLON.Matrix.Identity();
  81248. /**
  81249. * References to the webVR controllers for the vrDevice.
  81250. */
  81251. _this.controllers = [];
  81252. /**
  81253. * Emits an event when a controller is attached.
  81254. */
  81255. _this.onControllersAttachedObservable = new BABYLON.Observable();
  81256. /**
  81257. * Emits an event when a controller's mesh has been loaded;
  81258. */
  81259. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  81260. /**
  81261. * If the rig cameras be used as parent instead of this camera.
  81262. */
  81263. _this.rigParenting = true;
  81264. _this._defaultHeight = undefined;
  81265. _this._workingVector = BABYLON.Vector3.Zero();
  81266. _this._oneVector = BABYLON.Vector3.One();
  81267. _this._workingMatrix = BABYLON.Matrix.Identity();
  81268. _this._cache.position = BABYLON.Vector3.Zero();
  81269. if (webVROptions.defaultHeight) {
  81270. _this._defaultHeight = webVROptions.defaultHeight;
  81271. _this.position.y = _this._defaultHeight;
  81272. }
  81273. _this.minZ = 0.1;
  81274. //legacy support - the compensation boolean was removed.
  81275. if (arguments.length === 5) {
  81276. _this.webVROptions = arguments[4];
  81277. }
  81278. // default webVR options
  81279. if (_this.webVROptions.trackPosition == undefined) {
  81280. _this.webVROptions.trackPosition = true;
  81281. }
  81282. if (_this.webVROptions.controllerMeshes == undefined) {
  81283. _this.webVROptions.controllerMeshes = true;
  81284. }
  81285. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  81286. _this.webVROptions.defaultLightingOnControllers = true;
  81287. }
  81288. _this.rotationQuaternion = new BABYLON.Quaternion();
  81289. if (_this.webVROptions && _this.webVROptions.positionScale) {
  81290. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  81291. }
  81292. //enable VR
  81293. var engine = _this.getEngine();
  81294. _this._onVREnabled = function (success) { if (success) {
  81295. _this.initControllers();
  81296. } };
  81297. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  81298. engine.initWebVR().add(function (event) {
  81299. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  81300. return;
  81301. }
  81302. _this._vrDevice = event.vrDisplay;
  81303. //reset the rig parameters.
  81304. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  81305. if (_this._attached) {
  81306. _this.getEngine().enableVR();
  81307. }
  81308. });
  81309. if (typeof (VRFrameData) !== "undefined")
  81310. _this._frameData = new VRFrameData();
  81311. /**
  81312. * The idea behind the following lines:
  81313. * objects that have the camera as parent should actually have the rig cameras as a parent.
  81314. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  81315. * the second will not show it correctly.
  81316. *
  81317. * To solve this - each object that has the camera as parent will be added to a protected array.
  81318. * When the rig camera renders, it will take this array and set all of those to be its children.
  81319. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  81320. * Amazing!
  81321. */
  81322. scene.onBeforeCameraRenderObservable.add(function (camera) {
  81323. if (camera.parent === _this && _this.rigParenting) {
  81324. _this._descendants = _this.getDescendants(true, function (n) {
  81325. // don't take the cameras or the controllers!
  81326. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  81327. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  81328. return !isController && !isRigCamera;
  81329. });
  81330. _this._descendants.forEach(function (node) {
  81331. node.parent = camera;
  81332. });
  81333. }
  81334. });
  81335. scene.onAfterCameraRenderObservable.add(function (camera) {
  81336. if (camera.parent === _this && _this.rigParenting) {
  81337. _this._descendants.forEach(function (node) {
  81338. node.parent = _this;
  81339. });
  81340. }
  81341. });
  81342. return _this;
  81343. }
  81344. /**
  81345. * Gets the device distance from the ground in meters.
  81346. * @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.
  81347. */
  81348. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  81349. if (this._standingMatrix) {
  81350. // Add standing matrix offset to get real offset from ground in room
  81351. this._standingMatrix.getTranslationToRef(this._workingVector);
  81352. return this._deviceRoomPosition.y + this._workingVector.y;
  81353. }
  81354. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  81355. return this._defaultHeight || 0;
  81356. };
  81357. /**
  81358. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  81359. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  81360. */
  81361. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  81362. var _this = this;
  81363. if (callback === void 0) { callback = function (bool) { }; }
  81364. // Use standing matrix if available
  81365. this.getEngine().initWebVRAsync().then(function (result) {
  81366. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  81367. callback(false);
  81368. }
  81369. else {
  81370. _this._standingMatrix = new BABYLON.Matrix();
  81371. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  81372. if (!_this.getScene().useRightHandedSystem) {
  81373. [2, 6, 8, 9, 14].forEach(function (num) {
  81374. if (_this._standingMatrix) {
  81375. _this._standingMatrix.m[num] *= -1;
  81376. }
  81377. });
  81378. }
  81379. callback(true);
  81380. }
  81381. });
  81382. };
  81383. /**
  81384. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  81385. * @returns A promise with a boolean set to if the standing matrix is supported.
  81386. */
  81387. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  81388. var _this = this;
  81389. return new Promise(function (res, rej) {
  81390. _this.useStandingMatrix(function (supported) {
  81391. res(supported);
  81392. });
  81393. });
  81394. };
  81395. /**
  81396. * Disposes the camera
  81397. */
  81398. WebVRFreeCamera.prototype.dispose = function () {
  81399. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  81400. _super.prototype.dispose.call(this);
  81401. };
  81402. /**
  81403. * Gets a vrController by name.
  81404. * @param name The name of the controller to retreive
  81405. * @returns the controller matching the name specified or null if not found
  81406. */
  81407. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  81408. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  81409. var gp = _a[_i];
  81410. if (gp.hand === name) {
  81411. return gp;
  81412. }
  81413. }
  81414. return null;
  81415. };
  81416. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  81417. /**
  81418. * The controller corrisponding to the users left hand.
  81419. */
  81420. get: function () {
  81421. if (!this._leftController) {
  81422. this._leftController = this.getControllerByName("left");
  81423. }
  81424. return this._leftController;
  81425. },
  81426. enumerable: true,
  81427. configurable: true
  81428. });
  81429. ;
  81430. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  81431. /**
  81432. * The controller corrisponding to the users right hand.
  81433. */
  81434. get: function () {
  81435. if (!this._rightController) {
  81436. this._rightController = this.getControllerByName("right");
  81437. }
  81438. return this._rightController;
  81439. },
  81440. enumerable: true,
  81441. configurable: true
  81442. });
  81443. ;
  81444. /**
  81445. * Casts a ray forward from the vrCamera's gaze.
  81446. * @param length Length of the ray (default: 100)
  81447. * @returns the ray corrisponding to the gaze
  81448. */
  81449. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  81450. if (length === void 0) { length = 100; }
  81451. if (this.leftCamera) {
  81452. // Use left eye to avoid computation to compute center on every call
  81453. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  81454. }
  81455. else {
  81456. return _super.prototype.getForwardRay.call(this, length);
  81457. }
  81458. };
  81459. /**
  81460. * Updates the camera based on device's frame data
  81461. */
  81462. WebVRFreeCamera.prototype._checkInputs = function () {
  81463. if (this._vrDevice && this._vrDevice.isPresenting) {
  81464. this._vrDevice.getFrameData(this._frameData);
  81465. this.updateFromDevice(this._frameData.pose);
  81466. }
  81467. _super.prototype._checkInputs.call(this);
  81468. };
  81469. /**
  81470. * Updates the poseControlled values based on the input device pose.
  81471. * @param poseData Pose coming from the device
  81472. */
  81473. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  81474. if (poseData && poseData.orientation) {
  81475. this.rawPose = poseData;
  81476. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  81477. if (this.getScene().useRightHandedSystem) {
  81478. this._deviceRoomRotationQuaternion.z *= -1;
  81479. this._deviceRoomRotationQuaternion.w *= -1;
  81480. }
  81481. if (this.webVROptions.trackPosition && this.rawPose.position) {
  81482. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  81483. if (this.getScene().useRightHandedSystem) {
  81484. this._deviceRoomPosition.z *= -1;
  81485. }
  81486. }
  81487. }
  81488. };
  81489. /**
  81490. * WebVR's attach control will start broadcasting frames to the device.
  81491. * Note that in certain browsers (chrome for example) this function must be called
  81492. * within a user-interaction callback. Example:
  81493. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  81494. *
  81495. * @param element html element to attach the vrDevice to
  81496. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  81497. */
  81498. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  81499. _super.prototype.attachControl.call(this, element, noPreventDefault);
  81500. this._attached = true;
  81501. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  81502. if (this._vrDevice) {
  81503. this.getEngine().enableVR();
  81504. }
  81505. };
  81506. /**
  81507. * Detaches the camera from the html element and disables VR
  81508. *
  81509. * @param element html element to detach from
  81510. */
  81511. WebVRFreeCamera.prototype.detachControl = function (element) {
  81512. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  81513. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  81514. _super.prototype.detachControl.call(this, element);
  81515. this._attached = false;
  81516. this.getEngine().disableVR();
  81517. };
  81518. /**
  81519. * @returns the name of this class
  81520. */
  81521. WebVRFreeCamera.prototype.getClassName = function () {
  81522. return "WebVRFreeCamera";
  81523. };
  81524. /**
  81525. * Calls resetPose on the vrDisplay
  81526. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  81527. */
  81528. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  81529. //uses the vrDisplay's "resetPose()".
  81530. //pitch and roll won't be affected.
  81531. this._vrDevice.resetPose();
  81532. };
  81533. /**
  81534. * Updates the rig cameras (left and right eye)
  81535. */
  81536. WebVRFreeCamera.prototype._updateRigCameras = function () {
  81537. var camLeft = this._rigCameras[0];
  81538. var camRight = this._rigCameras[1];
  81539. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  81540. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  81541. camLeft.position.copyFrom(this._deviceRoomPosition);
  81542. camRight.position.copyFrom(this._deviceRoomPosition);
  81543. };
  81544. /**
  81545. * Updates the cached values of the camera
  81546. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  81547. */
  81548. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  81549. var _this = this;
  81550. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  81551. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  81552. if (!this.updateCacheCalled) {
  81553. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  81554. this.updateCacheCalled = true;
  81555. this.update();
  81556. }
  81557. // Set working vector to the device position in room space rotated by the new rotation
  81558. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  81559. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  81560. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  81561. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  81562. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  81563. // Add translation from anchor position
  81564. this._deviceToWorld.getTranslationToRef(this._workingVector);
  81565. this._workingVector.addInPlace(this.position);
  81566. this._workingVector.subtractInPlace(this._cache.position);
  81567. this._deviceToWorld.setTranslation(this._workingVector);
  81568. // Set an inverted matrix to be used when updating the camera
  81569. this._deviceToWorld.invertToRef(this._worldToDevice);
  81570. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  81571. this.controllers.forEach(function (controller) {
  81572. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  81573. controller.update();
  81574. });
  81575. }
  81576. if (!ignoreParentClass) {
  81577. _super.prototype._updateCache.call(this);
  81578. }
  81579. this.updateCacheCalled = false;
  81580. };
  81581. /**
  81582. * Updates the current device position and rotation in the babylon world
  81583. */
  81584. WebVRFreeCamera.prototype.update = function () {
  81585. // Get current device position in babylon world
  81586. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  81587. // Get current device rotation in babylon world
  81588. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  81589. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  81590. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  81591. _super.prototype.update.call(this);
  81592. };
  81593. /**
  81594. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  81595. * @returns an identity matrix
  81596. */
  81597. WebVRFreeCamera.prototype._getViewMatrix = function () {
  81598. return BABYLON.Matrix.Identity();
  81599. };
  81600. /**
  81601. * This function is called by the two RIG cameras.
  81602. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  81603. */
  81604. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  81605. var _this = this;
  81606. // Update the parent camera prior to using a child camera to avoid desynchronization
  81607. var parentCamera = this._cameraRigParams["parentCamera"];
  81608. parentCamera._updateCache();
  81609. //WebVR 1.1
  81610. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  81611. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  81612. if (!this.getScene().useRightHandedSystem) {
  81613. [2, 6, 8, 9, 14].forEach(function (num) {
  81614. _this._webvrViewMatrix.m[num] *= -1;
  81615. });
  81616. }
  81617. // update the camera rotation matrix
  81618. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  81619. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  81620. // Computing target and final matrix
  81621. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  81622. // should the view matrix be updated with scale and position offset?
  81623. if (parentCamera.deviceScaleFactor !== 1) {
  81624. this._webvrViewMatrix.invert();
  81625. // scale the position, if set
  81626. if (parentCamera.deviceScaleFactor) {
  81627. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  81628. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  81629. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  81630. }
  81631. this._webvrViewMatrix.invert();
  81632. }
  81633. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  81634. return this._webvrViewMatrix;
  81635. };
  81636. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  81637. var _this = this;
  81638. var parentCamera = this.parent;
  81639. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  81640. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  81641. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  81642. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  81643. //babylon compatible matrix
  81644. if (!this.getScene().useRightHandedSystem) {
  81645. [8, 9, 10, 11].forEach(function (num) {
  81646. _this._projectionMatrix.m[num] *= -1;
  81647. });
  81648. }
  81649. return this._projectionMatrix;
  81650. };
  81651. /**
  81652. * Initializes the controllers and their meshes
  81653. */
  81654. WebVRFreeCamera.prototype.initControllers = function () {
  81655. var _this = this;
  81656. this.controllers = [];
  81657. var manager = this.getScene().gamepadManager;
  81658. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  81659. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  81660. var webVrController = gamepad;
  81661. if (webVrController.defaultModel) {
  81662. webVrController.defaultModel.setEnabled(false);
  81663. }
  81664. if (webVrController.hand === "right") {
  81665. _this._rightController = null;
  81666. }
  81667. if (webVrController.hand === "left") {
  81668. _this._leftController = null;
  81669. }
  81670. var controllerIndex = _this.controllers.indexOf(webVrController);
  81671. if (controllerIndex !== -1) {
  81672. _this.controllers.splice(controllerIndex, 1);
  81673. }
  81674. }
  81675. });
  81676. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  81677. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  81678. var webVrController_1 = gamepad;
  81679. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  81680. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  81681. if (_this.webVROptions.controllerMeshes) {
  81682. if (webVrController_1.defaultModel) {
  81683. webVrController_1.defaultModel.setEnabled(true);
  81684. }
  81685. else {
  81686. // Load the meshes
  81687. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  81688. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  81689. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  81690. if (_this.webVROptions.defaultLightingOnControllers) {
  81691. if (!_this._lightOnControllers) {
  81692. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  81693. }
  81694. var activateLightOnSubMeshes_1 = function (mesh, light) {
  81695. var children = mesh.getChildren();
  81696. if (children.length !== 0) {
  81697. children.forEach(function (mesh) {
  81698. light.includedOnlyMeshes.push(mesh);
  81699. activateLightOnSubMeshes_1(mesh, light);
  81700. });
  81701. }
  81702. };
  81703. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  81704. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  81705. }
  81706. });
  81707. }
  81708. }
  81709. webVrController_1.attachToPoseControlledCamera(_this);
  81710. // since this is async - sanity check. Is the controller already stored?
  81711. if (_this.controllers.indexOf(webVrController_1) === -1) {
  81712. //add to the controllers array
  81713. _this.controllers.push(webVrController_1);
  81714. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  81715. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  81716. // So we're overriding setting left & right manually to be sure
  81717. var firstViveWandDetected = false;
  81718. for (var i = 0; i < _this.controllers.length; i++) {
  81719. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  81720. if (!firstViveWandDetected) {
  81721. firstViveWandDetected = true;
  81722. _this.controllers[i].hand = "left";
  81723. }
  81724. else {
  81725. _this.controllers[i].hand = "right";
  81726. }
  81727. }
  81728. }
  81729. //did we find enough controllers? Great! let the developer know.
  81730. if (_this.controllers.length >= 2) {
  81731. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  81732. }
  81733. }
  81734. }
  81735. });
  81736. };
  81737. return WebVRFreeCamera;
  81738. }(BABYLON.FreeCamera));
  81739. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  81740. })(BABYLON || (BABYLON = {}));
  81741. //# sourceMappingURL=babylon.webVRCamera.js.map
  81742. var BABYLON;
  81743. (function (BABYLON) {
  81744. // We're mainly based on the logic defined into the FreeCamera code
  81745. /**
  81746. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  81747. * being tilted forward or back and left or right.
  81748. */
  81749. var DeviceOrientationCamera = /** @class */ (function (_super) {
  81750. __extends(DeviceOrientationCamera, _super);
  81751. /**
  81752. * Creates a new device orientation camera. @see DeviceOrientationCamera
  81753. * @param name The name of the camera
  81754. * @param position The start position camera
  81755. * @param scene The scene the camera belongs to
  81756. */
  81757. function DeviceOrientationCamera(name, position, scene) {
  81758. var _this = _super.call(this, name, position, scene) || this;
  81759. _this._quaternionCache = new BABYLON.Quaternion();
  81760. _this.inputs.addDeviceOrientation();
  81761. return _this;
  81762. }
  81763. /**
  81764. * Gets the current instance class name ("DeviceOrientationCamera").
  81765. * This helps avoiding instanceof at run time.
  81766. * @returns the class name
  81767. */
  81768. DeviceOrientationCamera.prototype.getClassName = function () {
  81769. return "DeviceOrientationCamera";
  81770. };
  81771. /**
  81772. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  81773. */
  81774. DeviceOrientationCamera.prototype._checkInputs = function () {
  81775. _super.prototype._checkInputs.call(this);
  81776. this._quaternionCache.copyFrom(this.rotationQuaternion);
  81777. if (this._initialQuaternion) {
  81778. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  81779. }
  81780. };
  81781. /**
  81782. * Reset the camera to its default orientation on the specified axis only.
  81783. * @param axis The axis to reset
  81784. */
  81785. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  81786. var _this = this;
  81787. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  81788. //can only work if this camera has a rotation quaternion already.
  81789. if (!this.rotationQuaternion)
  81790. return;
  81791. if (!this._initialQuaternion) {
  81792. this._initialQuaternion = new BABYLON.Quaternion();
  81793. }
  81794. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  81795. ['x', 'y', 'z'].forEach(function (axisName) {
  81796. if (!axis[axisName]) {
  81797. _this._initialQuaternion[axisName] = 0;
  81798. }
  81799. else {
  81800. _this._initialQuaternion[axisName] *= -1;
  81801. }
  81802. });
  81803. this._initialQuaternion.normalize();
  81804. //force rotation update
  81805. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  81806. };
  81807. return DeviceOrientationCamera;
  81808. }(BABYLON.FreeCamera));
  81809. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  81810. })(BABYLON || (BABYLON = {}));
  81811. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  81812. var BABYLON;
  81813. (function (BABYLON) {
  81814. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  81815. __extends(VRDeviceOrientationFreeCamera, _super);
  81816. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  81817. if (compensateDistortion === void 0) { compensateDistortion = true; }
  81818. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  81819. var _this = _super.call(this, name, position, scene) || this;
  81820. vrCameraMetrics.compensateDistortion = compensateDistortion;
  81821. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  81822. return _this;
  81823. }
  81824. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  81825. return "VRDeviceOrientationFreeCamera";
  81826. };
  81827. return VRDeviceOrientationFreeCamera;
  81828. }(BABYLON.DeviceOrientationCamera));
  81829. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  81830. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  81831. __extends(VRDeviceOrientationGamepadCamera, _super);
  81832. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  81833. if (compensateDistortion === void 0) { compensateDistortion = true; }
  81834. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  81835. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  81836. _this.inputs.addGamepad();
  81837. return _this;
  81838. }
  81839. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  81840. return "VRDeviceOrientationGamepadCamera";
  81841. };
  81842. return VRDeviceOrientationGamepadCamera;
  81843. }(VRDeviceOrientationFreeCamera));
  81844. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  81845. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  81846. __extends(VRDeviceOrientationArcRotateCamera, _super);
  81847. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  81848. if (compensateDistortion === void 0) { compensateDistortion = true; }
  81849. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  81850. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  81851. vrCameraMetrics.compensateDistortion = compensateDistortion;
  81852. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  81853. _this.inputs.addVRDeviceOrientation();
  81854. return _this;
  81855. }
  81856. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  81857. return "VRDeviceOrientationArcRotateCamera";
  81858. };
  81859. return VRDeviceOrientationArcRotateCamera;
  81860. }(BABYLON.ArcRotateCamera));
  81861. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  81862. })(BABYLON || (BABYLON = {}));
  81863. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  81864. var BABYLON;
  81865. (function (BABYLON) {
  81866. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  81867. __extends(AnaglyphFreeCamera, _super);
  81868. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  81869. var _this = _super.call(this, name, position, scene) || this;
  81870. _this.interaxialDistance = interaxialDistance;
  81871. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81872. return _this;
  81873. }
  81874. AnaglyphFreeCamera.prototype.getClassName = function () {
  81875. return "AnaglyphFreeCamera";
  81876. };
  81877. return AnaglyphFreeCamera;
  81878. }(BABYLON.FreeCamera));
  81879. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  81880. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  81881. __extends(AnaglyphArcRotateCamera, _super);
  81882. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  81883. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  81884. _this.interaxialDistance = interaxialDistance;
  81885. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81886. return _this;
  81887. }
  81888. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  81889. return "AnaglyphArcRotateCamera";
  81890. };
  81891. return AnaglyphArcRotateCamera;
  81892. }(BABYLON.ArcRotateCamera));
  81893. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  81894. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  81895. __extends(AnaglyphGamepadCamera, _super);
  81896. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  81897. var _this = _super.call(this, name, position, scene) || this;
  81898. _this.interaxialDistance = interaxialDistance;
  81899. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81900. return _this;
  81901. }
  81902. AnaglyphGamepadCamera.prototype.getClassName = function () {
  81903. return "AnaglyphGamepadCamera";
  81904. };
  81905. return AnaglyphGamepadCamera;
  81906. }(BABYLON.GamepadCamera));
  81907. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  81908. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  81909. __extends(AnaglyphUniversalCamera, _super);
  81910. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  81911. var _this = _super.call(this, name, position, scene) || this;
  81912. _this.interaxialDistance = interaxialDistance;
  81913. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81914. return _this;
  81915. }
  81916. AnaglyphUniversalCamera.prototype.getClassName = function () {
  81917. return "AnaglyphUniversalCamera";
  81918. };
  81919. return AnaglyphUniversalCamera;
  81920. }(BABYLON.UniversalCamera));
  81921. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  81922. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  81923. __extends(StereoscopicFreeCamera, _super);
  81924. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  81925. var _this = _super.call(this, name, position, scene) || this;
  81926. _this.interaxialDistance = interaxialDistance;
  81927. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81928. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81929. return _this;
  81930. }
  81931. StereoscopicFreeCamera.prototype.getClassName = function () {
  81932. return "StereoscopicFreeCamera";
  81933. };
  81934. return StereoscopicFreeCamera;
  81935. }(BABYLON.FreeCamera));
  81936. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  81937. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  81938. __extends(StereoscopicArcRotateCamera, _super);
  81939. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  81940. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  81941. _this.interaxialDistance = interaxialDistance;
  81942. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81943. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81944. return _this;
  81945. }
  81946. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  81947. return "StereoscopicArcRotateCamera";
  81948. };
  81949. return StereoscopicArcRotateCamera;
  81950. }(BABYLON.ArcRotateCamera));
  81951. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  81952. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  81953. __extends(StereoscopicGamepadCamera, _super);
  81954. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  81955. var _this = _super.call(this, name, position, scene) || this;
  81956. _this.interaxialDistance = interaxialDistance;
  81957. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81958. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81959. return _this;
  81960. }
  81961. StereoscopicGamepadCamera.prototype.getClassName = function () {
  81962. return "StereoscopicGamepadCamera";
  81963. };
  81964. return StereoscopicGamepadCamera;
  81965. }(BABYLON.GamepadCamera));
  81966. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  81967. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  81968. __extends(StereoscopicUniversalCamera, _super);
  81969. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  81970. var _this = _super.call(this, name, position, scene) || this;
  81971. _this.interaxialDistance = interaxialDistance;
  81972. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81973. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81974. return _this;
  81975. }
  81976. StereoscopicUniversalCamera.prototype.getClassName = function () {
  81977. return "StereoscopicUniversalCamera";
  81978. };
  81979. return StereoscopicUniversalCamera;
  81980. }(BABYLON.UniversalCamera));
  81981. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  81982. })(BABYLON || (BABYLON = {}));
  81983. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  81984. var BABYLON;
  81985. (function (BABYLON) {
  81986. var VRExperienceHelperGazer = /** @class */ (function () {
  81987. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  81988. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  81989. this.scene = scene;
  81990. this._pointerDownOnMeshAsked = false;
  81991. this._isActionableMesh = false;
  81992. this._teleportationRequestInitiated = false;
  81993. this._teleportationBackRequestInitiated = false;
  81994. this._dpadPressed = true;
  81995. this._activePointer = false;
  81996. this._id = VRExperienceHelperGazer._idCounter++;
  81997. // Gaze tracker
  81998. if (!gazeTrackerToClone) {
  81999. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  82000. this._gazeTracker.bakeCurrentTransformIntoVertices();
  82001. this._gazeTracker.isPickable = false;
  82002. this._gazeTracker.isVisible = false;
  82003. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  82004. targetMat.specularColor = BABYLON.Color3.Black();
  82005. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  82006. targetMat.backFaceCulling = false;
  82007. this._gazeTracker.material = targetMat;
  82008. }
  82009. else {
  82010. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  82011. }
  82012. }
  82013. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  82014. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  82015. };
  82016. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  82017. this._pointerDownOnMeshAsked = true;
  82018. if (this._currentMeshSelected && this._currentHit) {
  82019. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  82020. }
  82021. };
  82022. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  82023. if (this._currentMeshSelected && this._currentHit) {
  82024. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  82025. }
  82026. this._pointerDownOnMeshAsked = false;
  82027. };
  82028. VRExperienceHelperGazer.prototype._activatePointer = function () {
  82029. this._activePointer = true;
  82030. };
  82031. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  82032. this._activePointer = false;
  82033. };
  82034. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  82035. };
  82036. VRExperienceHelperGazer.prototype.dispose = function () {
  82037. this._interactionsEnabled = false;
  82038. this._teleportationEnabled = false;
  82039. };
  82040. VRExperienceHelperGazer._idCounter = 0;
  82041. return VRExperienceHelperGazer;
  82042. }());
  82043. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  82044. __extends(VRExperienceHelperControllerGazer, _super);
  82045. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  82046. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  82047. _this.webVRController = webVRController;
  82048. // Laser pointer
  82049. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  82050. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  82051. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  82052. laserPointerMaterial.alpha = 0.6;
  82053. _this._laserPointer.material = laserPointerMaterial;
  82054. _this._laserPointer.rotation.x = Math.PI / 2;
  82055. _this._laserPointer.position.z = -0.5;
  82056. _this._laserPointer.isVisible = false;
  82057. if (!webVRController.mesh) {
  82058. // Create an empty mesh that is used prior to loading the high quality model
  82059. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  82060. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  82061. preloadPointerPose.rotation.x = -0.7;
  82062. preloadMesh.addChild(preloadPointerPose);
  82063. webVRController.attachToMesh(preloadMesh);
  82064. }
  82065. _this._setLaserPointerParent(webVRController.mesh);
  82066. return _this;
  82067. }
  82068. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  82069. return this.webVRController.getForwardRay(length);
  82070. };
  82071. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  82072. _super.prototype._activatePointer.call(this);
  82073. this._laserPointer.isVisible = true;
  82074. };
  82075. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  82076. _super.prototype._deactivatePointer.call(this);
  82077. this._laserPointer.isVisible = false;
  82078. };
  82079. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  82080. this._laserPointer.material.emissiveColor = color;
  82081. };
  82082. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  82083. var makeNotPick = function (root) {
  82084. root.name += " laserPointer";
  82085. root.getChildMeshes().forEach(function (c) {
  82086. makeNotPick(c);
  82087. });
  82088. };
  82089. makeNotPick(mesh);
  82090. var childMeshes = mesh.getChildMeshes();
  82091. this.webVRController._pointingPoseNode = null;
  82092. for (var i = 0; i < childMeshes.length; i++) {
  82093. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  82094. mesh = childMeshes[i];
  82095. this.webVRController._pointingPoseNode = mesh;
  82096. break;
  82097. }
  82098. }
  82099. this._laserPointer.parent = mesh;
  82100. };
  82101. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  82102. this._laserPointer.scaling.y = distance;
  82103. this._laserPointer.position.z = -distance / 2;
  82104. };
  82105. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  82106. _super.prototype.dispose.call(this);
  82107. this._laserPointer.dispose();
  82108. };
  82109. return VRExperienceHelperControllerGazer;
  82110. }(VRExperienceHelperGazer));
  82111. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  82112. __extends(VRExperienceHelperCameraGazer, _super);
  82113. function VRExperienceHelperCameraGazer(getCamera, scene) {
  82114. var _this = _super.call(this, scene) || this;
  82115. _this.getCamera = getCamera;
  82116. return _this;
  82117. }
  82118. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  82119. var camera = this.getCamera();
  82120. if (camera) {
  82121. return camera.getForwardRay(length);
  82122. }
  82123. else {
  82124. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  82125. }
  82126. };
  82127. return VRExperienceHelperCameraGazer;
  82128. }(VRExperienceHelperGazer));
  82129. /**
  82130. * Helps to quickly add VR support to an existing scene.
  82131. * See http://doc.babylonjs.com/how_to/webvr_helper
  82132. */
  82133. var VRExperienceHelper = /** @class */ (function () {
  82134. /**
  82135. * Instantiates a VRExperienceHelper.
  82136. * Helps to quickly add VR support to an existing scene.
  82137. * @param scene The scene the VRExperienceHelper belongs to.
  82138. * @param webVROptions Options to modify the vr experience helper's behavior.
  82139. */
  82140. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  82141. if (webVROptions === void 0) { webVROptions = {}; }
  82142. var _this = this;
  82143. this.webVROptions = webVROptions;
  82144. // Can the system support WebVR, even if a headset isn't plugged in?
  82145. this._webVRsupported = false;
  82146. // If WebVR is supported, is a headset plugged in and are we ready to present?
  82147. this._webVRready = false;
  82148. // Are we waiting for the requestPresent callback to complete?
  82149. this._webVRrequesting = false;
  82150. // Are we presenting to the headset right now?
  82151. this._webVRpresenting = false;
  82152. // Are we presenting in the fullscreen fallback?
  82153. this._fullscreenVRpresenting = false;
  82154. /**
  82155. * Observable raised when entering VR.
  82156. */
  82157. this.onEnteringVRObservable = new BABYLON.Observable();
  82158. /**
  82159. * Observable raised when exiting VR.
  82160. */
  82161. this.onExitingVRObservable = new BABYLON.Observable();
  82162. /**
  82163. * Observable raised when controller mesh is loaded.
  82164. */
  82165. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  82166. this._useCustomVRButton = false;
  82167. this._teleportationRequested = false;
  82168. this._teleportActive = false;
  82169. this._floorMeshesCollection = [];
  82170. this._rotationAllowed = true;
  82171. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  82172. this._rotationRightAsked = false;
  82173. this._rotationLeftAsked = false;
  82174. this._isDefaultTeleportationTarget = true;
  82175. this._teleportationFillColor = "#444444";
  82176. this._teleportationBorderColor = "#FFFFFF";
  82177. this._rotationAngle = 0;
  82178. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  82179. this._padSensibilityUp = 0.65;
  82180. this._padSensibilityDown = 0.35;
  82181. this.leftController = null;
  82182. this.rightController = null;
  82183. /**
  82184. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  82185. */
  82186. this.onNewMeshSelected = new BABYLON.Observable();
  82187. /**
  82188. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  82189. */
  82190. this.onNewMeshPicked = new BABYLON.Observable();
  82191. /**
  82192. * Observable raised before camera teleportation
  82193. */
  82194. this.onBeforeCameraTeleport = new BABYLON.Observable();
  82195. /**
  82196. * Observable raised after camera teleportation
  82197. */
  82198. this.onAfterCameraTeleport = new BABYLON.Observable();
  82199. /**
  82200. * Observable raised when current selected mesh gets unselected
  82201. */
  82202. this.onSelectedMeshUnselected = new BABYLON.Observable();
  82203. /**
  82204. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  82205. */
  82206. this.teleportationEnabled = true;
  82207. this._teleportationInitialized = false;
  82208. this._interactionsEnabled = false;
  82209. this._interactionsRequested = false;
  82210. this._displayGaze = true;
  82211. this._displayLaserPointer = true;
  82212. this._onResize = function () {
  82213. _this.moveButtonToBottomRight();
  82214. if (_this._fullscreenVRpresenting && _this._webVRready) {
  82215. _this.exitVR();
  82216. }
  82217. };
  82218. this._onFullscreenChange = function () {
  82219. if (document.fullscreen !== undefined) {
  82220. _this._fullscreenVRpresenting = document.fullscreen;
  82221. }
  82222. else if (document.mozFullScreen !== undefined) {
  82223. _this._fullscreenVRpresenting = document.mozFullScreen;
  82224. }
  82225. else if (document.webkitIsFullScreen !== undefined) {
  82226. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  82227. }
  82228. else if (document.msIsFullScreen !== undefined) {
  82229. _this._fullscreenVRpresenting = document.msIsFullScreen;
  82230. }
  82231. if (!_this._fullscreenVRpresenting && _this._canvas) {
  82232. _this.exitVR();
  82233. if (!_this._useCustomVRButton) {
  82234. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  82235. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  82236. }
  82237. }
  82238. };
  82239. this.beforeRender = function () {
  82240. if (_this.leftController && _this.leftController._activePointer) {
  82241. _this._castRayAndSelectObject(_this.leftController);
  82242. }
  82243. if (_this.rightController && _this.rightController._activePointer) {
  82244. _this._castRayAndSelectObject(_this.rightController);
  82245. }
  82246. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  82247. _this._castRayAndSelectObject(_this._cameraGazer);
  82248. }
  82249. else {
  82250. _this._cameraGazer._gazeTracker.isVisible = false;
  82251. }
  82252. };
  82253. this._onNewGamepadConnected = function (gamepad) {
  82254. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  82255. if (gamepad.leftStick) {
  82256. gamepad.onleftstickchanged(function (stickValues) {
  82257. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  82258. // Listening to classic/xbox gamepad only if no VR controller is active
  82259. if ((!_this.leftController && !_this.rightController) ||
  82260. ((_this.leftController && !_this.leftController._activePointer) &&
  82261. (_this.rightController && !_this.rightController._activePointer))) {
  82262. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  82263. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  82264. }
  82265. }
  82266. });
  82267. }
  82268. if (gamepad.rightStick) {
  82269. gamepad.onrightstickchanged(function (stickValues) {
  82270. if (_this._teleportationInitialized) {
  82271. _this._checkRotate(stickValues, _this._cameraGazer);
  82272. }
  82273. });
  82274. }
  82275. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  82276. gamepad.onbuttondown(function (buttonPressed) {
  82277. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  82278. _this._cameraGazer._selectionPointerDown();
  82279. }
  82280. });
  82281. gamepad.onbuttonup(function (buttonPressed) {
  82282. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  82283. _this._cameraGazer._selectionPointerUp();
  82284. }
  82285. });
  82286. }
  82287. }
  82288. else {
  82289. var webVRController = gamepad;
  82290. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  82291. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  82292. _this.rightController = controller;
  82293. }
  82294. else {
  82295. _this.leftController = controller;
  82296. }
  82297. _this._tryEnableInteractionOnController(controller);
  82298. }
  82299. };
  82300. // 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
  82301. this._tryEnableInteractionOnController = function (controller) {
  82302. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  82303. _this._enableInteractionOnController(controller);
  82304. }
  82305. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  82306. _this._enableTeleportationOnController(controller);
  82307. }
  82308. };
  82309. this._onNewGamepadDisconnected = function (gamepad) {
  82310. if (gamepad instanceof BABYLON.WebVRController) {
  82311. if (gamepad.hand === "left" && _this.leftController != null) {
  82312. _this.leftController.dispose();
  82313. _this.leftController = null;
  82314. }
  82315. if (gamepad.hand === "right" && _this.rightController != null) {
  82316. _this.rightController.dispose();
  82317. _this.rightController = null;
  82318. }
  82319. }
  82320. };
  82321. this._workingVector = BABYLON.Vector3.Zero();
  82322. this._workingQuaternion = BABYLON.Quaternion.Identity();
  82323. this._workingMatrix = BABYLON.Matrix.Identity();
  82324. this._scene = scene;
  82325. this._canvas = scene.getEngine().getRenderingCanvas();
  82326. // Parse options
  82327. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  82328. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  82329. }
  82330. if (webVROptions.createDeviceOrientationCamera === undefined) {
  82331. webVROptions.createDeviceOrientationCamera = true;
  82332. }
  82333. if (webVROptions.defaultHeight === undefined) {
  82334. webVROptions.defaultHeight = 1.7;
  82335. }
  82336. if (webVROptions.useCustomVRButton) {
  82337. this._useCustomVRButton = true;
  82338. if (webVROptions.customVRButton) {
  82339. this._btnVR = webVROptions.customVRButton;
  82340. }
  82341. }
  82342. if (webVROptions.rayLength) {
  82343. this._rayLength = webVROptions.rayLength;
  82344. }
  82345. this._defaultHeight = webVROptions.defaultHeight;
  82346. if (webVROptions.positionScale) {
  82347. this._rayLength *= webVROptions.positionScale;
  82348. this._defaultHeight *= webVROptions.positionScale;
  82349. }
  82350. // Set position
  82351. if (this._scene.activeCamera) {
  82352. this._position = this._scene.activeCamera.position.clone();
  82353. }
  82354. else {
  82355. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  82356. }
  82357. // Set non-vr camera
  82358. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  82359. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  82360. // Copy data from existing camera
  82361. if (this._scene.activeCamera) {
  82362. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  82363. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  82364. // Set rotation from previous camera
  82365. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  82366. var targetCamera = this._scene.activeCamera;
  82367. if (targetCamera.rotationQuaternion) {
  82368. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  82369. }
  82370. else {
  82371. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  82372. }
  82373. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  82374. }
  82375. }
  82376. this._scene.activeCamera = this._deviceOrientationCamera;
  82377. if (this._canvas) {
  82378. this._scene.activeCamera.attachControl(this._canvas);
  82379. }
  82380. }
  82381. else {
  82382. this._existingCamera = this._scene.activeCamera;
  82383. }
  82384. // Create VR cameras
  82385. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  82386. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  82387. }
  82388. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  82389. this._webVRCamera.useStandingMatrix();
  82390. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  82391. // Create default button
  82392. if (!this._useCustomVRButton) {
  82393. this._btnVR = document.createElement("BUTTON");
  82394. this._btnVR.className = "babylonVRicon";
  82395. this._btnVR.id = "babylonVRiconbtn";
  82396. this._btnVR.title = "Click to switch to VR";
  82397. 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) }";
  82398. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  82399. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  82400. // css += ".babylonVRicon.vrdisplaysupported { }";
  82401. // css += ".babylonVRicon.vrdisplayready { }";
  82402. // css += ".babylonVRicon.vrdisplayrequesting { }";
  82403. var style = document.createElement('style');
  82404. style.appendChild(document.createTextNode(css));
  82405. document.getElementsByTagName('head')[0].appendChild(style);
  82406. this.moveButtonToBottomRight();
  82407. }
  82408. // VR button click event
  82409. if (this._btnVR) {
  82410. this._btnVR.addEventListener("click", function () {
  82411. if (!_this.isInVRMode) {
  82412. _this.enterVR();
  82413. }
  82414. else {
  82415. _this.exitVR();
  82416. }
  82417. });
  82418. }
  82419. // Window events
  82420. window.addEventListener("resize", this._onResize);
  82421. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  82422. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  82423. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  82424. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  82425. // Display vr button when headset is connected
  82426. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  82427. this.displayVRButton();
  82428. }
  82429. else {
  82430. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  82431. if (e.vrDisplay) {
  82432. _this.displayVRButton();
  82433. }
  82434. });
  82435. }
  82436. // Exiting VR mode using 'ESC' key on desktop
  82437. this._onKeyDown = function (event) {
  82438. if (event.keyCode === 27 && _this.isInVRMode) {
  82439. _this.exitVR();
  82440. }
  82441. };
  82442. document.addEventListener("keydown", this._onKeyDown);
  82443. // Exiting VR mode double tapping the touch screen
  82444. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  82445. if (_this.isInVRMode) {
  82446. _this.exitVR();
  82447. if (_this._fullscreenVRpresenting) {
  82448. _this._scene.getEngine().switchFullscreen(true);
  82449. }
  82450. }
  82451. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  82452. // Listen for WebVR display changes
  82453. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  82454. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  82455. this._onVRRequestPresentStart = function () {
  82456. _this._webVRrequesting = true;
  82457. _this.updateButtonVisibility();
  82458. };
  82459. this._onVRRequestPresentComplete = function (success) {
  82460. _this._webVRrequesting = false;
  82461. _this.updateButtonVisibility();
  82462. };
  82463. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  82464. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  82465. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  82466. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  82467. scene.onDisposeObservable.add(function () {
  82468. _this.dispose();
  82469. });
  82470. // Gamepad connection events
  82471. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  82472. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  82473. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  82474. this.updateButtonVisibility();
  82475. //create easing functions
  82476. this._circleEase = new BABYLON.CircleEase();
  82477. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  82478. }
  82479. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  82480. /** Return this.onEnteringVRObservable
  82481. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  82482. */
  82483. get: function () {
  82484. return this.onEnteringVRObservable;
  82485. },
  82486. enumerable: true,
  82487. configurable: true
  82488. });
  82489. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  82490. /** Return this.onExitingVRObservable
  82491. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  82492. */
  82493. get: function () {
  82494. return this.onExitingVRObservable;
  82495. },
  82496. enumerable: true,
  82497. configurable: true
  82498. });
  82499. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  82500. /** Return this.onControllerMeshLoadedObservable
  82501. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  82502. */
  82503. get: function () {
  82504. return this.onControllerMeshLoadedObservable;
  82505. },
  82506. enumerable: true,
  82507. configurable: true
  82508. });
  82509. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  82510. /**
  82511. * The mesh used to display where the user is going to teleport.
  82512. */
  82513. get: function () {
  82514. return this._teleportationTarget;
  82515. },
  82516. /**
  82517. * Sets the mesh to be used to display where the user is going to teleport.
  82518. */
  82519. set: function (value) {
  82520. if (value) {
  82521. value.name = "teleportationTarget";
  82522. this._isDefaultTeleportationTarget = false;
  82523. this._teleportationTarget = value;
  82524. }
  82525. },
  82526. enumerable: true,
  82527. configurable: true
  82528. });
  82529. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  82530. /**
  82531. * The mesh used to display where the user is selecting,
  82532. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  82533. * See http://doc.babylonjs.com/resources/baking_transformations
  82534. */
  82535. get: function () {
  82536. return this._cameraGazer._gazeTracker;
  82537. },
  82538. set: function (value) {
  82539. if (value) {
  82540. this._cameraGazer._gazeTracker = value;
  82541. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  82542. this._cameraGazer._gazeTracker.isPickable = false;
  82543. this._cameraGazer._gazeTracker.isVisible = false;
  82544. this._cameraGazer._gazeTracker.name = "gazeTracker";
  82545. if (this.leftController) {
  82546. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  82547. }
  82548. if (this.rightController) {
  82549. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  82550. }
  82551. }
  82552. },
  82553. enumerable: true,
  82554. configurable: true
  82555. });
  82556. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  82557. /**
  82558. * If the ray of the gaze should be displayed.
  82559. */
  82560. get: function () {
  82561. return this._displayGaze;
  82562. },
  82563. /**
  82564. * Sets if the ray of the gaze should be displayed.
  82565. */
  82566. set: function (value) {
  82567. this._displayGaze = value;
  82568. if (!value) {
  82569. this._cameraGazer._gazeTracker.isVisible = false;
  82570. if (this.leftController) {
  82571. this.leftController._gazeTracker.isVisible = false;
  82572. }
  82573. if (this.rightController) {
  82574. this.rightController._gazeTracker.isVisible = false;
  82575. }
  82576. }
  82577. },
  82578. enumerable: true,
  82579. configurable: true
  82580. });
  82581. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  82582. /**
  82583. * If the ray of the LaserPointer should be displayed.
  82584. */
  82585. get: function () {
  82586. return this._displayLaserPointer;
  82587. },
  82588. /**
  82589. * Sets if the ray of the LaserPointer should be displayed.
  82590. */
  82591. set: function (value) {
  82592. this._displayLaserPointer = value;
  82593. if (!value) {
  82594. if (this.rightController) {
  82595. this.rightController._deactivatePointer();
  82596. this.rightController._gazeTracker.isVisible = false;
  82597. }
  82598. if (this.leftController) {
  82599. this.leftController._deactivatePointer();
  82600. this.leftController._gazeTracker.isVisible = false;
  82601. }
  82602. }
  82603. else {
  82604. if (this.rightController) {
  82605. this.rightController._activatePointer();
  82606. }
  82607. else if (this.leftController) {
  82608. this.leftController._activatePointer();
  82609. }
  82610. }
  82611. },
  82612. enumerable: true,
  82613. configurable: true
  82614. });
  82615. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  82616. /**
  82617. * The deviceOrientationCamera used as the camera when not in VR.
  82618. */
  82619. get: function () {
  82620. return this._deviceOrientationCamera;
  82621. },
  82622. enumerable: true,
  82623. configurable: true
  82624. });
  82625. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  82626. /**
  82627. * Based on the current WebVR support, returns the current VR camera used.
  82628. */
  82629. get: function () {
  82630. if (this._webVRready) {
  82631. return this._webVRCamera;
  82632. }
  82633. else {
  82634. return this._scene.activeCamera;
  82635. }
  82636. },
  82637. enumerable: true,
  82638. configurable: true
  82639. });
  82640. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  82641. /**
  82642. * The webVRCamera which is used when in VR.
  82643. */
  82644. get: function () {
  82645. return this._webVRCamera;
  82646. },
  82647. enumerable: true,
  82648. configurable: true
  82649. });
  82650. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  82651. /**
  82652. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  82653. */
  82654. get: function () {
  82655. return this._vrDeviceOrientationCamera;
  82656. },
  82657. enumerable: true,
  82658. configurable: true
  82659. });
  82660. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  82661. get: function () {
  82662. var result = this._cameraGazer._teleportationRequestInitiated
  82663. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  82664. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  82665. return result;
  82666. },
  82667. enumerable: true,
  82668. configurable: true
  82669. });
  82670. // Raised when one of the controller has loaded successfully its associated default mesh
  82671. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  82672. if (this.leftController && this.leftController.webVRController == webVRController) {
  82673. if (webVRController.mesh) {
  82674. this.leftController._setLaserPointerParent(webVRController.mesh);
  82675. }
  82676. }
  82677. if (this.rightController && this.rightController.webVRController == webVRController) {
  82678. if (webVRController.mesh) {
  82679. this.rightController._setLaserPointerParent(webVRController.mesh);
  82680. }
  82681. }
  82682. try {
  82683. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  82684. }
  82685. catch (err) {
  82686. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  82687. }
  82688. };
  82689. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  82690. /**
  82691. * Gets a value indicating if we are currently in VR mode.
  82692. */
  82693. get: function () {
  82694. return this._webVRpresenting || this._fullscreenVRpresenting;
  82695. },
  82696. enumerable: true,
  82697. configurable: true
  82698. });
  82699. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  82700. var vrDisplay = this._scene.getEngine().getVRDevice();
  82701. if (vrDisplay) {
  82702. var wasPresenting = this._webVRpresenting;
  82703. // A VR display is connected
  82704. this._webVRpresenting = vrDisplay.isPresenting;
  82705. if (wasPresenting && !this._webVRpresenting)
  82706. this.exitVR();
  82707. }
  82708. else {
  82709. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  82710. }
  82711. this.updateButtonVisibility();
  82712. };
  82713. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  82714. this._webVRsupported = eventArgs.vrSupported;
  82715. this._webVRready = !!eventArgs.vrDisplay;
  82716. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  82717. this.updateButtonVisibility();
  82718. };
  82719. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  82720. if (this._canvas && !this._useCustomVRButton) {
  82721. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  82722. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  82723. }
  82724. };
  82725. VRExperienceHelper.prototype.displayVRButton = function () {
  82726. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  82727. document.body.appendChild(this._btnVR);
  82728. this._btnVRDisplayed = true;
  82729. }
  82730. };
  82731. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  82732. if (!this._btnVR || this._useCustomVRButton) {
  82733. return;
  82734. }
  82735. this._btnVR.className = "babylonVRicon";
  82736. if (this.isInVRMode) {
  82737. this._btnVR.className += " vrdisplaypresenting";
  82738. }
  82739. else {
  82740. if (this._webVRready)
  82741. this._btnVR.className += " vrdisplayready";
  82742. if (this._webVRsupported)
  82743. this._btnVR.className += " vrdisplaysupported";
  82744. if (this._webVRrequesting)
  82745. this._btnVR.className += " vrdisplayrequesting";
  82746. }
  82747. };
  82748. /**
  82749. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  82750. * Otherwise, will use the fullscreen API.
  82751. */
  82752. VRExperienceHelper.prototype.enterVR = function () {
  82753. if (this.onEnteringVRObservable) {
  82754. try {
  82755. this.onEnteringVRObservable.notifyObservers(this);
  82756. }
  82757. catch (err) {
  82758. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  82759. }
  82760. }
  82761. if (this._scene.activeCamera) {
  82762. this._position = this._scene.activeCamera.position.clone();
  82763. // make sure that we return to the last active camera
  82764. this._existingCamera = this._scene.activeCamera;
  82765. }
  82766. if (this._webVRrequesting)
  82767. return;
  82768. // If WebVR is supported and a headset is connected
  82769. if (this._webVRready) {
  82770. if (!this._webVRpresenting) {
  82771. this._webVRCamera.position = this._position;
  82772. this._scene.activeCamera = this._webVRCamera;
  82773. }
  82774. }
  82775. else if (this._vrDeviceOrientationCamera) {
  82776. this._vrDeviceOrientationCamera.position = this._position;
  82777. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  82778. this._scene.getEngine().switchFullscreen(true);
  82779. this.updateButtonVisibility();
  82780. }
  82781. if (this._scene.activeCamera && this._canvas) {
  82782. this._scene.activeCamera.attachControl(this._canvas);
  82783. }
  82784. if (this._interactionsEnabled) {
  82785. this._scene.registerBeforeRender(this.beforeRender);
  82786. }
  82787. };
  82788. /**
  82789. * Attempt to exit VR, or fullscreen.
  82790. */
  82791. VRExperienceHelper.prototype.exitVR = function () {
  82792. if (this.onExitingVRObservable) {
  82793. try {
  82794. this.onExitingVRObservable.notifyObservers(this);
  82795. }
  82796. catch (err) {
  82797. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  82798. }
  82799. }
  82800. if (this._webVRpresenting) {
  82801. this._scene.getEngine().disableVR();
  82802. }
  82803. if (this._scene.activeCamera) {
  82804. this._position = this._scene.activeCamera.position.clone();
  82805. }
  82806. if (this._deviceOrientationCamera) {
  82807. this._deviceOrientationCamera.position = this._position;
  82808. this._scene.activeCamera = this._deviceOrientationCamera;
  82809. if (this._canvas) {
  82810. this._scene.activeCamera.attachControl(this._canvas);
  82811. }
  82812. }
  82813. else if (this._existingCamera) {
  82814. this._existingCamera.position = this._position;
  82815. this._scene.activeCamera = this._existingCamera;
  82816. }
  82817. this.updateButtonVisibility();
  82818. if (this._interactionsEnabled) {
  82819. this._scene.unregisterBeforeRender(this.beforeRender);
  82820. }
  82821. };
  82822. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  82823. /**
  82824. * The position of the vr experience helper.
  82825. */
  82826. get: function () {
  82827. return this._position;
  82828. },
  82829. /**
  82830. * Sets the position of the vr experience helper.
  82831. */
  82832. set: function (value) {
  82833. this._position = value;
  82834. if (this._scene.activeCamera) {
  82835. this._scene.activeCamera.position = value;
  82836. }
  82837. },
  82838. enumerable: true,
  82839. configurable: true
  82840. });
  82841. /**
  82842. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  82843. */
  82844. VRExperienceHelper.prototype.enableInteractions = function () {
  82845. var _this = this;
  82846. if (!this._interactionsEnabled) {
  82847. this._interactionsRequested = true;
  82848. if (this.leftController) {
  82849. this._enableInteractionOnController(this.leftController);
  82850. }
  82851. if (this.rightController) {
  82852. this._enableInteractionOnController(this.rightController);
  82853. }
  82854. this.raySelectionPredicate = function (mesh) {
  82855. return mesh.isVisible;
  82856. };
  82857. this.meshSelectionPredicate = function (mesh) {
  82858. return true;
  82859. };
  82860. this._raySelectionPredicate = function (mesh) {
  82861. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  82862. && mesh.name.indexOf("teleportationTarget") === -1
  82863. && mesh.name.indexOf("torusTeleportation") === -1
  82864. && mesh.name.indexOf("laserPointer") === -1)) {
  82865. return _this.raySelectionPredicate(mesh);
  82866. }
  82867. return false;
  82868. };
  82869. this._interactionsEnabled = true;
  82870. }
  82871. };
  82872. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  82873. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  82874. if (this._floorMeshesCollection[i].id === mesh.id) {
  82875. return true;
  82876. }
  82877. }
  82878. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  82879. return true;
  82880. }
  82881. return false;
  82882. };
  82883. /**
  82884. * Adds a floor mesh to be used for teleportation.
  82885. * @param floorMesh the mesh to be used for teleportation.
  82886. */
  82887. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  82888. if (!this._floorMeshesCollection) {
  82889. return;
  82890. }
  82891. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  82892. return;
  82893. }
  82894. this._floorMeshesCollection.push(floorMesh);
  82895. };
  82896. /**
  82897. * Removes a floor mesh from being used for teleportation.
  82898. * @param floorMesh the mesh to be removed.
  82899. */
  82900. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  82901. if (!this._floorMeshesCollection) {
  82902. return;
  82903. }
  82904. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  82905. if (meshIndex !== -1) {
  82906. this._floorMeshesCollection.splice(meshIndex, 1);
  82907. }
  82908. };
  82909. /**
  82910. * Enables interactions and teleportation using the VR controllers and gaze.
  82911. * @param vrTeleportationOptions options to modify teleportation behavior.
  82912. */
  82913. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  82914. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  82915. if (!this._teleportationInitialized) {
  82916. this._teleportationRequested = true;
  82917. this.enableInteractions();
  82918. if (vrTeleportationOptions.floorMeshName) {
  82919. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  82920. }
  82921. if (vrTeleportationOptions.floorMeshes) {
  82922. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  82923. }
  82924. if (this.leftController != null) {
  82925. this._enableTeleportationOnController(this.leftController);
  82926. }
  82927. if (this.rightController != null) {
  82928. this._enableTeleportationOnController(this.rightController);
  82929. }
  82930. // Creates an image processing post process for the vignette not relying
  82931. // on the main scene configuration for image processing to reduce setup and spaces
  82932. // (gamma/linear) conflicts.
  82933. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  82934. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  82935. imageProcessingConfiguration.vignetteEnabled = true;
  82936. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  82937. this._webVRCamera.detachPostProcess(this._postProcessMove);
  82938. this._teleportationInitialized = true;
  82939. if (this._isDefaultTeleportationTarget) {
  82940. this._createTeleportationCircles();
  82941. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  82942. }
  82943. }
  82944. };
  82945. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  82946. var _this = this;
  82947. var controllerMesh = controller.webVRController.mesh;
  82948. if (controllerMesh) {
  82949. controller._interactionsEnabled = true;
  82950. controller._activatePointer();
  82951. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  82952. // Enabling / disabling laserPointer
  82953. if (_this._displayLaserPointer && stateObject.value === 1) {
  82954. if (controller._activePointer) {
  82955. controller._deactivatePointer();
  82956. }
  82957. else {
  82958. controller._activatePointer();
  82959. }
  82960. if (_this.displayGaze) {
  82961. controller._gazeTracker.isVisible = controller._activePointer;
  82962. }
  82963. }
  82964. });
  82965. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  82966. if (!controller._pointerDownOnMeshAsked) {
  82967. if (stateObject.value > _this._padSensibilityUp) {
  82968. controller._selectionPointerDown();
  82969. }
  82970. }
  82971. else if (stateObject.value < _this._padSensibilityDown) {
  82972. controller._selectionPointerUp();
  82973. }
  82974. });
  82975. }
  82976. };
  82977. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  82978. // Dont teleport if another gaze already requested teleportation
  82979. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  82980. return;
  82981. }
  82982. if (!gazer._teleportationRequestInitiated) {
  82983. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  82984. gazer._activatePointer();
  82985. gazer._teleportationRequestInitiated = true;
  82986. }
  82987. }
  82988. else {
  82989. // Listening to the proper controller values changes to confirm teleportation
  82990. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  82991. if (this._teleportActive) {
  82992. this._teleportCamera(this._haloCenter);
  82993. }
  82994. gazer._teleportationRequestInitiated = false;
  82995. }
  82996. }
  82997. };
  82998. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  82999. // Only rotate when user is not currently selecting a teleportation location
  83000. if (gazer._teleportationRequestInitiated) {
  83001. return;
  83002. }
  83003. if (!this._rotationLeftAsked) {
  83004. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  83005. this._rotationLeftAsked = true;
  83006. if (this._rotationAllowed) {
  83007. this._rotateCamera(false);
  83008. }
  83009. }
  83010. }
  83011. else {
  83012. if (stateObject.x > -this._padSensibilityDown) {
  83013. this._rotationLeftAsked = false;
  83014. }
  83015. }
  83016. if (!this._rotationRightAsked) {
  83017. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  83018. this._rotationRightAsked = true;
  83019. if (this._rotationAllowed) {
  83020. this._rotateCamera(true);
  83021. }
  83022. }
  83023. }
  83024. else {
  83025. if (stateObject.x < this._padSensibilityDown) {
  83026. this._rotationRightAsked = false;
  83027. }
  83028. }
  83029. };
  83030. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  83031. // Only teleport backwards when user is not currently selecting a teleportation location
  83032. if (gazer._teleportationRequestInitiated) {
  83033. return;
  83034. }
  83035. // Teleport backwards
  83036. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  83037. if (!gazer._teleportationBackRequestInitiated) {
  83038. if (!this.currentVRCamera) {
  83039. return;
  83040. }
  83041. // Get rotation and position of the current camera
  83042. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  83043. var position = this.currentVRCamera.position;
  83044. // If the camera has device position, use that instead
  83045. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  83046. rotation = this.currentVRCamera.deviceRotationQuaternion;
  83047. position = this.currentVRCamera.devicePosition;
  83048. }
  83049. // Get matrix with only the y rotation of the device rotation
  83050. rotation.toEulerAnglesToRef(this._workingVector);
  83051. this._workingVector.z = 0;
  83052. this._workingVector.x = 0;
  83053. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  83054. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  83055. // Rotate backwards ray by device rotation to cast at the ground behind the user
  83056. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  83057. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  83058. var ray = new BABYLON.Ray(position, this._workingVector);
  83059. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  83060. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  83061. this._teleportCamera(hit.pickedPoint);
  83062. }
  83063. gazer._teleportationBackRequestInitiated = true;
  83064. }
  83065. }
  83066. else {
  83067. gazer._teleportationBackRequestInitiated = false;
  83068. }
  83069. };
  83070. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  83071. var _this = this;
  83072. var controllerMesh = controller.webVRController.mesh;
  83073. if (controllerMesh) {
  83074. if (!controller._interactionsEnabled) {
  83075. this._enableInteractionOnController(controller);
  83076. }
  83077. controller._interactionsEnabled = true;
  83078. controller._teleportationEnabled = true;
  83079. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  83080. controller._dpadPressed = false;
  83081. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  83082. controller._dpadPressed = stateObject.pressed;
  83083. if (!controller._dpadPressed) {
  83084. _this._rotationLeftAsked = false;
  83085. _this._rotationRightAsked = false;
  83086. controller._teleportationBackRequestInitiated = false;
  83087. }
  83088. });
  83089. }
  83090. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  83091. if (_this.teleportationEnabled) {
  83092. _this._checkTeleportBackwards(stateObject, controller);
  83093. _this._checkTeleportWithRay(stateObject, controller);
  83094. }
  83095. _this._checkRotate(stateObject, controller);
  83096. });
  83097. }
  83098. };
  83099. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  83100. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  83101. this._teleportationTarget.isPickable = false;
  83102. var length = 512;
  83103. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  83104. dynamicTexture.hasAlpha = true;
  83105. var context = dynamicTexture.getContext();
  83106. var centerX = length / 2;
  83107. var centerY = length / 2;
  83108. var radius = 200;
  83109. context.beginPath();
  83110. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  83111. context.fillStyle = this._teleportationFillColor;
  83112. context.fill();
  83113. context.lineWidth = 10;
  83114. context.strokeStyle = this._teleportationBorderColor;
  83115. context.stroke();
  83116. context.closePath();
  83117. dynamicTexture.update();
  83118. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  83119. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  83120. this._teleportationTarget.material = teleportationCircleMaterial;
  83121. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  83122. torus.isPickable = false;
  83123. torus.parent = this._teleportationTarget;
  83124. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  83125. var keys = [];
  83126. keys.push({
  83127. frame: 0,
  83128. value: 0
  83129. });
  83130. keys.push({
  83131. frame: 30,
  83132. value: 0.4
  83133. });
  83134. keys.push({
  83135. frame: 60,
  83136. value: 0
  83137. });
  83138. animationInnerCircle.setKeys(keys);
  83139. var easingFunction = new BABYLON.SineEase();
  83140. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  83141. animationInnerCircle.setEasingFunction(easingFunction);
  83142. torus.animations = [];
  83143. torus.animations.push(animationInnerCircle);
  83144. this._scene.beginAnimation(torus, 0, 60, true);
  83145. this._hideTeleportationTarget();
  83146. };
  83147. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  83148. this._teleportActive = true;
  83149. if (this._teleportationInitialized) {
  83150. this._teleportationTarget.isVisible = true;
  83151. if (this._isDefaultTeleportationTarget) {
  83152. this._teleportationTarget.getChildren()[0].isVisible = true;
  83153. }
  83154. }
  83155. };
  83156. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  83157. this._teleportActive = false;
  83158. if (this._teleportationInitialized) {
  83159. this._teleportationTarget.isVisible = false;
  83160. if (this._isDefaultTeleportationTarget) {
  83161. this._teleportationTarget.getChildren()[0].isVisible = false;
  83162. }
  83163. }
  83164. };
  83165. VRExperienceHelper.prototype._rotateCamera = function (right) {
  83166. var _this = this;
  83167. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  83168. return;
  83169. }
  83170. if (right) {
  83171. this._rotationAngle++;
  83172. }
  83173. else {
  83174. this._rotationAngle--;
  83175. }
  83176. this.currentVRCamera.animations = [];
  83177. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  83178. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83179. var animationRotationKeys = [];
  83180. animationRotationKeys.push({
  83181. frame: 0,
  83182. value: this.currentVRCamera.rotationQuaternion
  83183. });
  83184. animationRotationKeys.push({
  83185. frame: 6,
  83186. value: target
  83187. });
  83188. animationRotation.setKeys(animationRotationKeys);
  83189. animationRotation.setEasingFunction(this._circleEase);
  83190. this.currentVRCamera.animations.push(animationRotation);
  83191. this._postProcessMove.animations = [];
  83192. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83193. var vignetteWeightKeys = [];
  83194. vignetteWeightKeys.push({
  83195. frame: 0,
  83196. value: 0
  83197. });
  83198. vignetteWeightKeys.push({
  83199. frame: 3,
  83200. value: 4
  83201. });
  83202. vignetteWeightKeys.push({
  83203. frame: 6,
  83204. value: 0
  83205. });
  83206. animationPP.setKeys(vignetteWeightKeys);
  83207. animationPP.setEasingFunction(this._circleEase);
  83208. this._postProcessMove.animations.push(animationPP);
  83209. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83210. var vignetteStretchKeys = [];
  83211. vignetteStretchKeys.push({
  83212. frame: 0,
  83213. value: 0
  83214. });
  83215. vignetteStretchKeys.push({
  83216. frame: 3,
  83217. value: 10
  83218. });
  83219. vignetteStretchKeys.push({
  83220. frame: 6,
  83221. value: 0
  83222. });
  83223. animationPP2.setKeys(vignetteStretchKeys);
  83224. animationPP2.setEasingFunction(this._circleEase);
  83225. this._postProcessMove.animations.push(animationPP2);
  83226. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  83227. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  83228. this._postProcessMove.samples = 4;
  83229. this._webVRCamera.attachPostProcess(this._postProcessMove);
  83230. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  83231. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  83232. });
  83233. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  83234. };
  83235. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  83236. if (hit.pickedPoint) {
  83237. if (gazer._teleportationRequestInitiated) {
  83238. this._displayTeleportationTarget();
  83239. this._haloCenter.copyFrom(hit.pickedPoint);
  83240. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  83241. }
  83242. var pickNormal = hit.getNormal(true, false);
  83243. if (pickNormal) {
  83244. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  83245. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  83246. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  83247. }
  83248. this._teleportationTarget.position.y += 0.1;
  83249. }
  83250. };
  83251. VRExperienceHelper.prototype._teleportCamera = function (location) {
  83252. var _this = this;
  83253. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  83254. return;
  83255. }
  83256. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  83257. // offset of the headset from the anchor.
  83258. if (this.webVRCamera.leftCamera) {
  83259. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  83260. this._workingVector.subtractInPlace(this.webVRCamera.position);
  83261. location.subtractToRef(this._workingVector, this._workingVector);
  83262. }
  83263. else {
  83264. this._workingVector.copyFrom(location);
  83265. }
  83266. // Add height to account for user's height offset
  83267. if (this.isInVRMode) {
  83268. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  83269. }
  83270. else {
  83271. this._workingVector.y += this._defaultHeight;
  83272. }
  83273. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  83274. // Create animation from the camera's position to the new location
  83275. this.currentVRCamera.animations = [];
  83276. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83277. var animationCameraTeleportationKeys = [{
  83278. frame: 0,
  83279. value: this.currentVRCamera.position
  83280. },
  83281. {
  83282. frame: 11,
  83283. value: this._workingVector
  83284. }
  83285. ];
  83286. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  83287. animationCameraTeleportation.setEasingFunction(this._circleEase);
  83288. this.currentVRCamera.animations.push(animationCameraTeleportation);
  83289. this._postProcessMove.animations = [];
  83290. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83291. var vignetteWeightKeys = [];
  83292. vignetteWeightKeys.push({
  83293. frame: 0,
  83294. value: 0
  83295. });
  83296. vignetteWeightKeys.push({
  83297. frame: 5,
  83298. value: 8
  83299. });
  83300. vignetteWeightKeys.push({
  83301. frame: 11,
  83302. value: 0
  83303. });
  83304. animationPP.setKeys(vignetteWeightKeys);
  83305. this._postProcessMove.animations.push(animationPP);
  83306. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83307. var vignetteStretchKeys = [];
  83308. vignetteStretchKeys.push({
  83309. frame: 0,
  83310. value: 0
  83311. });
  83312. vignetteStretchKeys.push({
  83313. frame: 5,
  83314. value: 10
  83315. });
  83316. vignetteStretchKeys.push({
  83317. frame: 11,
  83318. value: 0
  83319. });
  83320. animationPP2.setKeys(vignetteStretchKeys);
  83321. this._postProcessMove.animations.push(animationPP2);
  83322. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  83323. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  83324. this._webVRCamera.attachPostProcess(this._postProcessMove);
  83325. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  83326. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  83327. });
  83328. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  83329. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  83330. });
  83331. this._hideTeleportationTarget();
  83332. };
  83333. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  83334. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  83335. return;
  83336. }
  83337. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  83338. // Moving the gazeTracker on the mesh face targetted
  83339. if (hit && hit.pickedPoint) {
  83340. if (this._displayGaze) {
  83341. var multiplier = 1;
  83342. gazer._gazeTracker.isVisible = true;
  83343. if (gazer._isActionableMesh) {
  83344. multiplier = 3;
  83345. }
  83346. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  83347. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  83348. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  83349. var pickNormal = hit.getNormal();
  83350. // To avoid z-fighting
  83351. var deltaFighting = 0.002;
  83352. if (pickNormal) {
  83353. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  83354. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  83355. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  83356. }
  83357. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  83358. if (gazer._gazeTracker.position.x < 0) {
  83359. gazer._gazeTracker.position.x += deltaFighting;
  83360. }
  83361. else {
  83362. gazer._gazeTracker.position.x -= deltaFighting;
  83363. }
  83364. if (gazer._gazeTracker.position.y < 0) {
  83365. gazer._gazeTracker.position.y += deltaFighting;
  83366. }
  83367. else {
  83368. gazer._gazeTracker.position.y -= deltaFighting;
  83369. }
  83370. if (gazer._gazeTracker.position.z < 0) {
  83371. gazer._gazeTracker.position.z += deltaFighting;
  83372. }
  83373. else {
  83374. gazer._gazeTracker.position.z -= deltaFighting;
  83375. }
  83376. }
  83377. // Changing the size of the laser pointer based on the distance from the targetted point
  83378. gazer._updatePointerDistance(hit.distance);
  83379. }
  83380. else {
  83381. gazer._gazeTracker.isVisible = false;
  83382. }
  83383. if (hit && hit.pickedMesh) {
  83384. gazer._currentHit = hit;
  83385. if (gazer._pointerDownOnMeshAsked) {
  83386. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  83387. }
  83388. // The object selected is the floor, we're in a teleportation scenario
  83389. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  83390. // Moving the teleportation area to this targetted point
  83391. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  83392. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  83393. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83394. }
  83395. gazer._currentMeshSelected = null;
  83396. if (gazer._teleportationRequestInitiated) {
  83397. this._moveTeleportationSelectorTo(hit, gazer);
  83398. }
  83399. return;
  83400. }
  83401. // If not, we're in a selection scenario
  83402. //this._teleportationAllowed = false;
  83403. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  83404. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  83405. this.onNewMeshPicked.notifyObservers(hit);
  83406. gazer._currentMeshSelected = hit.pickedMesh;
  83407. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  83408. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  83409. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  83410. gazer._isActionableMesh = true;
  83411. }
  83412. else {
  83413. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83414. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83415. gazer._isActionableMesh = false;
  83416. }
  83417. try {
  83418. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  83419. }
  83420. catch (err) {
  83421. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  83422. }
  83423. }
  83424. else {
  83425. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83426. gazer._currentMeshSelected = null;
  83427. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83428. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83429. }
  83430. }
  83431. }
  83432. else {
  83433. gazer._currentHit = null;
  83434. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83435. gazer._currentMeshSelected = null;
  83436. //this._teleportationAllowed = false;
  83437. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83438. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83439. }
  83440. };
  83441. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  83442. if (mesh) {
  83443. this.onSelectedMeshUnselected.notifyObservers(mesh);
  83444. }
  83445. };
  83446. /**
  83447. * Sets the color of the laser ray from the vr controllers.
  83448. * @param color new color for the ray.
  83449. */
  83450. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  83451. if (this.leftController) {
  83452. this.leftController._setLaserPointerColor(color);
  83453. }
  83454. if (this.rightController) {
  83455. this.rightController._setLaserPointerColor(color);
  83456. }
  83457. };
  83458. /**
  83459. * Sets the color of the ray from the vr headsets gaze.
  83460. * @param color new color for the ray.
  83461. */
  83462. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  83463. if (!this._cameraGazer._gazeTracker.material) {
  83464. return;
  83465. }
  83466. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  83467. if (this.leftController) {
  83468. this.leftController._gazeTracker.material.emissiveColor = color;
  83469. }
  83470. if (this.rightController) {
  83471. this.rightController._gazeTracker.material.emissiveColor = color;
  83472. }
  83473. };
  83474. /**
  83475. * Exits VR and disposes of the vr experience helper
  83476. */
  83477. VRExperienceHelper.prototype.dispose = function () {
  83478. if (this.isInVRMode) {
  83479. this.exitVR();
  83480. }
  83481. if (this._postProcessMove) {
  83482. this._postProcessMove.dispose();
  83483. }
  83484. if (this._webVRCamera) {
  83485. this._webVRCamera.dispose();
  83486. }
  83487. if (this._vrDeviceOrientationCamera) {
  83488. this._vrDeviceOrientationCamera.dispose();
  83489. }
  83490. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  83491. document.body.removeChild(this._btnVR);
  83492. }
  83493. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  83494. this._deviceOrientationCamera.dispose();
  83495. }
  83496. if (this._cameraGazer) {
  83497. this._cameraGazer.dispose();
  83498. }
  83499. if (this.leftController) {
  83500. this.leftController.dispose();
  83501. }
  83502. if (this.rightController) {
  83503. this.rightController.dispose();
  83504. }
  83505. if (this._teleportationTarget) {
  83506. this._teleportationTarget.dispose();
  83507. }
  83508. this._floorMeshesCollection = [];
  83509. document.removeEventListener("keydown", this._onKeyDown);
  83510. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  83511. window.removeEventListener("resize", this._onResize);
  83512. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  83513. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  83514. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  83515. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  83516. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  83517. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  83518. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  83519. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  83520. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  83521. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  83522. this._scene.unregisterBeforeRender(this.beforeRender);
  83523. };
  83524. /**
  83525. * Gets the name of the VRExperienceHelper class
  83526. * @returns "VRExperienceHelper"
  83527. */
  83528. VRExperienceHelper.prototype.getClassName = function () {
  83529. return "VRExperienceHelper";
  83530. };
  83531. return VRExperienceHelper;
  83532. }());
  83533. BABYLON.VRExperienceHelper = VRExperienceHelper;
  83534. })(BABYLON || (BABYLON = {}));
  83535. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  83536. // Mainly based on these 2 articles :
  83537. // 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
  83538. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  83539. var BABYLON;
  83540. (function (BABYLON) {
  83541. var JoystickAxis;
  83542. (function (JoystickAxis) {
  83543. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  83544. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  83545. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  83546. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  83547. var VirtualJoystick = /** @class */ (function () {
  83548. function VirtualJoystick(leftJoystick) {
  83549. var _this = this;
  83550. if (leftJoystick) {
  83551. this._leftJoystick = true;
  83552. }
  83553. else {
  83554. this._leftJoystick = false;
  83555. }
  83556. VirtualJoystick._globalJoystickIndex++;
  83557. // By default left & right arrow keys are moving the X
  83558. // and up & down keys are moving the Y
  83559. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  83560. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  83561. this.reverseLeftRight = false;
  83562. this.reverseUpDown = false;
  83563. // collections of pointers
  83564. this._touches = new BABYLON.StringDictionary();
  83565. this.deltaPosition = BABYLON.Vector3.Zero();
  83566. this._joystickSensibility = 25;
  83567. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  83568. this._onResize = function (evt) {
  83569. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  83570. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  83571. if (VirtualJoystick.vjCanvas) {
  83572. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  83573. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  83574. }
  83575. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  83576. };
  83577. // injecting a canvas element on top of the canvas 3D game
  83578. if (!VirtualJoystick.vjCanvas) {
  83579. window.addEventListener("resize", this._onResize, false);
  83580. VirtualJoystick.vjCanvas = document.createElement("canvas");
  83581. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  83582. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  83583. VirtualJoystick.vjCanvas.width = window.innerWidth;
  83584. VirtualJoystick.vjCanvas.height = window.innerHeight;
  83585. VirtualJoystick.vjCanvas.style.width = "100%";
  83586. VirtualJoystick.vjCanvas.style.height = "100%";
  83587. VirtualJoystick.vjCanvas.style.position = "absolute";
  83588. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  83589. VirtualJoystick.vjCanvas.style.top = "0px";
  83590. VirtualJoystick.vjCanvas.style.left = "0px";
  83591. VirtualJoystick.vjCanvas.style.zIndex = "5";
  83592. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  83593. // Support for jQuery PEP polyfill
  83594. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  83595. var context = VirtualJoystick.vjCanvas.getContext('2d');
  83596. if (!context) {
  83597. throw new Error("Unable to create canvas for virtual joystick");
  83598. }
  83599. VirtualJoystick.vjCanvasContext = context;
  83600. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  83601. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  83602. document.body.appendChild(VirtualJoystick.vjCanvas);
  83603. }
  83604. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  83605. this.pressed = false;
  83606. // default joystick color
  83607. this._joystickColor = "cyan";
  83608. this._joystickPointerID = -1;
  83609. // current joystick position
  83610. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  83611. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  83612. // origin joystick position
  83613. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  83614. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  83615. this._onPointerDownHandlerRef = function (evt) {
  83616. _this._onPointerDown(evt);
  83617. };
  83618. this._onPointerMoveHandlerRef = function (evt) {
  83619. _this._onPointerMove(evt);
  83620. };
  83621. this._onPointerUpHandlerRef = function (evt) {
  83622. _this._onPointerUp(evt);
  83623. };
  83624. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  83625. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  83626. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  83627. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  83628. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  83629. evt.preventDefault(); // Disables system menu
  83630. }, false);
  83631. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  83632. }
  83633. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  83634. this._joystickSensibility = newJoystickSensibility;
  83635. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  83636. };
  83637. VirtualJoystick.prototype._onPointerDown = function (e) {
  83638. var positionOnScreenCondition;
  83639. e.preventDefault();
  83640. if (this._leftJoystick === true) {
  83641. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  83642. }
  83643. else {
  83644. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  83645. }
  83646. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  83647. // First contact will be dedicated to the virtual joystick
  83648. this._joystickPointerID = e.pointerId;
  83649. this._joystickPointerStartPos.x = e.clientX;
  83650. this._joystickPointerStartPos.y = e.clientY;
  83651. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  83652. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  83653. this._deltaJoystickVector.x = 0;
  83654. this._deltaJoystickVector.y = 0;
  83655. this.pressed = true;
  83656. this._touches.add(e.pointerId.toString(), e);
  83657. }
  83658. else {
  83659. // You can only trigger the action buttons with a joystick declared
  83660. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  83661. this._action();
  83662. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  83663. }
  83664. }
  83665. };
  83666. VirtualJoystick.prototype._onPointerMove = function (e) {
  83667. // If the current pointer is the one associated to the joystick (first touch contact)
  83668. if (this._joystickPointerID == e.pointerId) {
  83669. this._joystickPointerPos.x = e.clientX;
  83670. this._joystickPointerPos.y = e.clientY;
  83671. this._deltaJoystickVector = this._joystickPointerPos.clone();
  83672. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  83673. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  83674. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  83675. switch (this._axisTargetedByLeftAndRight) {
  83676. case JoystickAxis.X:
  83677. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  83678. break;
  83679. case JoystickAxis.Y:
  83680. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  83681. break;
  83682. case JoystickAxis.Z:
  83683. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  83684. break;
  83685. }
  83686. var directionUpDown = this.reverseUpDown ? 1 : -1;
  83687. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  83688. switch (this._axisTargetedByUpAndDown) {
  83689. case JoystickAxis.X:
  83690. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  83691. break;
  83692. case JoystickAxis.Y:
  83693. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  83694. break;
  83695. case JoystickAxis.Z:
  83696. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  83697. break;
  83698. }
  83699. }
  83700. else {
  83701. var data = this._touches.get(e.pointerId.toString());
  83702. if (data) {
  83703. data.x = e.clientX;
  83704. data.y = e.clientY;
  83705. }
  83706. }
  83707. };
  83708. VirtualJoystick.prototype._onPointerUp = function (e) {
  83709. if (this._joystickPointerID == e.pointerId) {
  83710. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  83711. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  83712. this._joystickPointerID = -1;
  83713. this.pressed = false;
  83714. }
  83715. else {
  83716. var touch = this._touches.get(e.pointerId.toString());
  83717. if (touch) {
  83718. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  83719. }
  83720. }
  83721. this._deltaJoystickVector.x = 0;
  83722. this._deltaJoystickVector.y = 0;
  83723. this._touches.remove(e.pointerId.toString());
  83724. };
  83725. /**
  83726. * Change the color of the virtual joystick
  83727. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  83728. */
  83729. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  83730. this._joystickColor = newColor;
  83731. };
  83732. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  83733. this._action = action;
  83734. };
  83735. // Define which axis you'd like to control for left & right
  83736. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  83737. switch (axis) {
  83738. case JoystickAxis.X:
  83739. case JoystickAxis.Y:
  83740. case JoystickAxis.Z:
  83741. this._axisTargetedByLeftAndRight = axis;
  83742. break;
  83743. default:
  83744. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  83745. break;
  83746. }
  83747. };
  83748. // Define which axis you'd like to control for up & down
  83749. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  83750. switch (axis) {
  83751. case JoystickAxis.X:
  83752. case JoystickAxis.Y:
  83753. case JoystickAxis.Z:
  83754. this._axisTargetedByUpAndDown = axis;
  83755. break;
  83756. default:
  83757. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  83758. break;
  83759. }
  83760. };
  83761. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  83762. var _this = this;
  83763. if (this.pressed) {
  83764. this._touches.forEach(function (key, touch) {
  83765. if (touch.pointerId === _this._joystickPointerID) {
  83766. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  83767. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  83768. VirtualJoystick.vjCanvasContext.beginPath();
  83769. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  83770. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  83771. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  83772. VirtualJoystick.vjCanvasContext.stroke();
  83773. VirtualJoystick.vjCanvasContext.closePath();
  83774. VirtualJoystick.vjCanvasContext.beginPath();
  83775. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  83776. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  83777. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  83778. VirtualJoystick.vjCanvasContext.stroke();
  83779. VirtualJoystick.vjCanvasContext.closePath();
  83780. VirtualJoystick.vjCanvasContext.beginPath();
  83781. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  83782. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  83783. VirtualJoystick.vjCanvasContext.stroke();
  83784. VirtualJoystick.vjCanvasContext.closePath();
  83785. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  83786. }
  83787. else {
  83788. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  83789. VirtualJoystick.vjCanvasContext.beginPath();
  83790. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  83791. VirtualJoystick.vjCanvasContext.beginPath();
  83792. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  83793. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  83794. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  83795. VirtualJoystick.vjCanvasContext.stroke();
  83796. VirtualJoystick.vjCanvasContext.closePath();
  83797. touch.prevX = touch.x;
  83798. touch.prevY = touch.y;
  83799. }
  83800. ;
  83801. });
  83802. }
  83803. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  83804. };
  83805. VirtualJoystick.prototype.releaseCanvas = function () {
  83806. if (VirtualJoystick.vjCanvas) {
  83807. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  83808. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  83809. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  83810. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  83811. window.removeEventListener("resize", this._onResize);
  83812. document.body.removeChild(VirtualJoystick.vjCanvas);
  83813. VirtualJoystick.vjCanvas = null;
  83814. }
  83815. };
  83816. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  83817. VirtualJoystick._globalJoystickIndex = 0;
  83818. return VirtualJoystick;
  83819. }());
  83820. BABYLON.VirtualJoystick = VirtualJoystick;
  83821. })(BABYLON || (BABYLON = {}));
  83822. //# sourceMappingURL=babylon.virtualJoystick.js.map
  83823. var BABYLON;
  83824. (function (BABYLON) {
  83825. // We're mainly based on the logic defined into the FreeCamera code
  83826. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  83827. __extends(VirtualJoysticksCamera, _super);
  83828. function VirtualJoysticksCamera(name, position, scene) {
  83829. var _this = _super.call(this, name, position, scene) || this;
  83830. _this.inputs.addVirtualJoystick();
  83831. return _this;
  83832. }
  83833. VirtualJoysticksCamera.prototype.getClassName = function () {
  83834. return "VirtualJoysticksCamera";
  83835. };
  83836. return VirtualJoysticksCamera;
  83837. }(BABYLON.FreeCamera));
  83838. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  83839. })(BABYLON || (BABYLON = {}));
  83840. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  83841. var BABYLON;
  83842. (function (BABYLON) {
  83843. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  83844. function FreeCameraVirtualJoystickInput() {
  83845. }
  83846. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  83847. return this._leftjoystick;
  83848. };
  83849. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  83850. return this._rightjoystick;
  83851. };
  83852. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  83853. if (this._leftjoystick) {
  83854. var camera = this.camera;
  83855. var speed = camera._computeLocalCameraSpeed() * 50;
  83856. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  83857. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  83858. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  83859. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  83860. if (!this._leftjoystick.pressed) {
  83861. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  83862. }
  83863. if (!this._rightjoystick.pressed) {
  83864. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  83865. }
  83866. }
  83867. };
  83868. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  83869. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  83870. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  83871. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  83872. this._leftjoystick.setJoystickSensibility(0.15);
  83873. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  83874. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  83875. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  83876. this._rightjoystick.reverseUpDown = true;
  83877. this._rightjoystick.setJoystickSensibility(0.05);
  83878. this._rightjoystick.setJoystickColor("yellow");
  83879. };
  83880. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  83881. this._leftjoystick.releaseCanvas();
  83882. this._rightjoystick.releaseCanvas();
  83883. };
  83884. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  83885. return "FreeCameraVirtualJoystickInput";
  83886. };
  83887. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  83888. return "virtualJoystick";
  83889. };
  83890. return FreeCameraVirtualJoystickInput;
  83891. }());
  83892. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  83893. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  83894. })(BABYLON || (BABYLON = {}));
  83895. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  83896. var BABYLON;
  83897. (function (BABYLON) {
  83898. var SimplificationSettings = /** @class */ (function () {
  83899. function SimplificationSettings(quality, distance, optimizeMesh) {
  83900. this.quality = quality;
  83901. this.distance = distance;
  83902. this.optimizeMesh = optimizeMesh;
  83903. }
  83904. return SimplificationSettings;
  83905. }());
  83906. BABYLON.SimplificationSettings = SimplificationSettings;
  83907. var SimplificationQueue = /** @class */ (function () {
  83908. function SimplificationQueue() {
  83909. this.running = false;
  83910. this._simplificationArray = [];
  83911. }
  83912. SimplificationQueue.prototype.addTask = function (task) {
  83913. this._simplificationArray.push(task);
  83914. };
  83915. SimplificationQueue.prototype.executeNext = function () {
  83916. var task = this._simplificationArray.pop();
  83917. if (task) {
  83918. this.running = true;
  83919. this.runSimplification(task);
  83920. }
  83921. else {
  83922. this.running = false;
  83923. }
  83924. };
  83925. SimplificationQueue.prototype.runSimplification = function (task) {
  83926. var _this = this;
  83927. if (task.parallelProcessing) {
  83928. //parallel simplifier
  83929. task.settings.forEach(function (setting) {
  83930. var simplifier = _this.getSimplifier(task);
  83931. simplifier.simplify(setting, function (newMesh) {
  83932. task.mesh.addLODLevel(setting.distance, newMesh);
  83933. newMesh.isVisible = true;
  83934. //check if it is the last
  83935. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  83936. //all done, run the success callback.
  83937. task.successCallback();
  83938. }
  83939. _this.executeNext();
  83940. });
  83941. });
  83942. }
  83943. else {
  83944. //single simplifier.
  83945. var simplifier = this.getSimplifier(task);
  83946. var runDecimation = function (setting, callback) {
  83947. simplifier.simplify(setting, function (newMesh) {
  83948. task.mesh.addLODLevel(setting.distance, newMesh);
  83949. newMesh.isVisible = true;
  83950. //run the next quality level
  83951. callback();
  83952. });
  83953. };
  83954. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  83955. runDecimation(task.settings[loop.index], function () {
  83956. loop.executeNext();
  83957. });
  83958. }, function () {
  83959. //execution ended, run the success callback.
  83960. if (task.successCallback) {
  83961. task.successCallback();
  83962. }
  83963. _this.executeNext();
  83964. });
  83965. }
  83966. };
  83967. SimplificationQueue.prototype.getSimplifier = function (task) {
  83968. switch (task.simplificationType) {
  83969. case SimplificationType.QUADRATIC:
  83970. default:
  83971. return new QuadraticErrorSimplification(task.mesh);
  83972. }
  83973. };
  83974. return SimplificationQueue;
  83975. }());
  83976. BABYLON.SimplificationQueue = SimplificationQueue;
  83977. /**
  83978. * The implemented types of simplification.
  83979. * At the moment only Quadratic Error Decimation is implemented.
  83980. */
  83981. var SimplificationType;
  83982. (function (SimplificationType) {
  83983. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  83984. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  83985. var DecimationTriangle = /** @class */ (function () {
  83986. function DecimationTriangle(vertices) {
  83987. this.vertices = vertices;
  83988. this.error = new Array(4);
  83989. this.deleted = false;
  83990. this.isDirty = false;
  83991. this.deletePending = false;
  83992. this.borderFactor = 0;
  83993. }
  83994. return DecimationTriangle;
  83995. }());
  83996. BABYLON.DecimationTriangle = DecimationTriangle;
  83997. var DecimationVertex = /** @class */ (function () {
  83998. function DecimationVertex(position, id) {
  83999. this.position = position;
  84000. this.id = id;
  84001. this.isBorder = true;
  84002. this.q = new QuadraticMatrix();
  84003. this.triangleCount = 0;
  84004. this.triangleStart = 0;
  84005. this.originalOffsets = [];
  84006. }
  84007. DecimationVertex.prototype.updatePosition = function (newPosition) {
  84008. this.position.copyFrom(newPosition);
  84009. };
  84010. return DecimationVertex;
  84011. }());
  84012. BABYLON.DecimationVertex = DecimationVertex;
  84013. var QuadraticMatrix = /** @class */ (function () {
  84014. function QuadraticMatrix(data) {
  84015. this.data = new Array(10);
  84016. for (var i = 0; i < 10; ++i) {
  84017. if (data && data[i]) {
  84018. this.data[i] = data[i];
  84019. }
  84020. else {
  84021. this.data[i] = 0;
  84022. }
  84023. }
  84024. }
  84025. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  84026. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  84027. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  84028. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  84029. return det;
  84030. };
  84031. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  84032. for (var i = 0; i < 10; ++i) {
  84033. this.data[i] += matrix.data[i];
  84034. }
  84035. };
  84036. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  84037. for (var i = 0; i < 10; ++i) {
  84038. this.data[i] += data[i];
  84039. }
  84040. };
  84041. QuadraticMatrix.prototype.add = function (matrix) {
  84042. var m = new QuadraticMatrix();
  84043. for (var i = 0; i < 10; ++i) {
  84044. m.data[i] = this.data[i] + matrix.data[i];
  84045. }
  84046. return m;
  84047. };
  84048. QuadraticMatrix.FromData = function (a, b, c, d) {
  84049. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  84050. };
  84051. //returning an array to avoid garbage collection
  84052. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  84053. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  84054. };
  84055. return QuadraticMatrix;
  84056. }());
  84057. BABYLON.QuadraticMatrix = QuadraticMatrix;
  84058. var Reference = /** @class */ (function () {
  84059. function Reference(vertexId, triangleId) {
  84060. this.vertexId = vertexId;
  84061. this.triangleId = triangleId;
  84062. }
  84063. return Reference;
  84064. }());
  84065. BABYLON.Reference = Reference;
  84066. /**
  84067. * An implementation of the Quadratic Error simplification algorithm.
  84068. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  84069. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  84070. * @author RaananW
  84071. */
  84072. var QuadraticErrorSimplification = /** @class */ (function () {
  84073. function QuadraticErrorSimplification(_mesh) {
  84074. this._mesh = _mesh;
  84075. this.syncIterations = 5000;
  84076. this.aggressiveness = 7;
  84077. this.decimationIterations = 100;
  84078. this.boundingBoxEpsilon = BABYLON.Epsilon;
  84079. }
  84080. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  84081. var _this = this;
  84082. this.initDecimatedMesh();
  84083. //iterating through the submeshes array, one after the other.
  84084. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  84085. _this.initWithMesh(loop.index, function () {
  84086. _this.runDecimation(settings, loop.index, function () {
  84087. loop.executeNext();
  84088. });
  84089. }, settings.optimizeMesh);
  84090. }, function () {
  84091. setTimeout(function () {
  84092. successCallback(_this._reconstructedMesh);
  84093. }, 0);
  84094. });
  84095. };
  84096. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  84097. var _this = this;
  84098. var targetCount = ~~(this.triangles.length * settings.quality);
  84099. var deletedTriangles = 0;
  84100. var triangleCount = this.triangles.length;
  84101. var iterationFunction = function (iteration, callback) {
  84102. setTimeout(function () {
  84103. if (iteration % 5 === 0) {
  84104. _this.updateMesh(iteration === 0);
  84105. }
  84106. for (var i = 0; i < _this.triangles.length; ++i) {
  84107. _this.triangles[i].isDirty = false;
  84108. }
  84109. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  84110. var trianglesIterator = function (i) {
  84111. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  84112. var t = _this.triangles[tIdx];
  84113. if (!t)
  84114. return;
  84115. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  84116. return;
  84117. }
  84118. for (var j = 0; j < 3; ++j) {
  84119. if (t.error[j] < threshold) {
  84120. var deleted0 = [];
  84121. var deleted1 = [];
  84122. var v0 = t.vertices[j];
  84123. var v1 = t.vertices[(j + 1) % 3];
  84124. if (v0.isBorder || v1.isBorder)
  84125. continue;
  84126. var p = BABYLON.Vector3.Zero();
  84127. var n = BABYLON.Vector3.Zero();
  84128. var uv = BABYLON.Vector2.Zero();
  84129. var color = new BABYLON.Color4(0, 0, 0, 1);
  84130. _this.calculateError(v0, v1, p, n, uv, color);
  84131. var delTr = new Array();
  84132. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  84133. continue;
  84134. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  84135. continue;
  84136. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  84137. continue;
  84138. var uniqueArray = new Array();
  84139. delTr.forEach(function (deletedT) {
  84140. if (uniqueArray.indexOf(deletedT) === -1) {
  84141. deletedT.deletePending = true;
  84142. uniqueArray.push(deletedT);
  84143. }
  84144. });
  84145. if (uniqueArray.length % 2 !== 0) {
  84146. continue;
  84147. }
  84148. v0.q = v1.q.add(v0.q);
  84149. v0.updatePosition(p);
  84150. var tStart = _this.references.length;
  84151. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  84152. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  84153. var tCount = _this.references.length - tStart;
  84154. if (tCount <= v0.triangleCount) {
  84155. if (tCount) {
  84156. for (var c = 0; c < tCount; c++) {
  84157. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  84158. }
  84159. }
  84160. }
  84161. else {
  84162. v0.triangleStart = tStart;
  84163. }
  84164. v0.triangleCount = tCount;
  84165. break;
  84166. }
  84167. }
  84168. };
  84169. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  84170. }, 0);
  84171. };
  84172. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  84173. if (triangleCount - deletedTriangles <= targetCount)
  84174. loop.breakLoop();
  84175. else {
  84176. iterationFunction(loop.index, function () {
  84177. loop.executeNext();
  84178. });
  84179. }
  84180. }, function () {
  84181. setTimeout(function () {
  84182. //reconstruct this part of the mesh
  84183. _this.reconstructMesh(submeshIndex);
  84184. successCallback();
  84185. }, 0);
  84186. });
  84187. };
  84188. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  84189. var _this = this;
  84190. this.vertices = [];
  84191. this.triangles = [];
  84192. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  84193. var indices = this._mesh.getIndices();
  84194. var submesh = this._mesh.subMeshes[submeshIndex];
  84195. var findInVertices = function (positionToSearch) {
  84196. if (optimizeMesh) {
  84197. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  84198. if (_this.vertices[ii].position.equals(positionToSearch)) {
  84199. return _this.vertices[ii];
  84200. }
  84201. }
  84202. }
  84203. return null;
  84204. };
  84205. var vertexReferences = [];
  84206. var vertexInit = function (i) {
  84207. if (!positionData) {
  84208. return;
  84209. }
  84210. var offset = i + submesh.verticesStart;
  84211. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  84212. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  84213. vertex.originalOffsets.push(offset);
  84214. if (vertex.id === _this.vertices.length) {
  84215. _this.vertices.push(vertex);
  84216. }
  84217. vertexReferences.push(vertex.id);
  84218. };
  84219. //var totalVertices = mesh.getTotalVertices();
  84220. var totalVertices = submesh.verticesCount;
  84221. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  84222. var indicesInit = function (i) {
  84223. if (!indices) {
  84224. return;
  84225. }
  84226. var offset = (submesh.indexStart / 3) + i;
  84227. var pos = (offset * 3);
  84228. var i0 = indices[pos + 0];
  84229. var i1 = indices[pos + 1];
  84230. var i2 = indices[pos + 2];
  84231. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  84232. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  84233. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  84234. var triangle = new DecimationTriangle([v0, v1, v2]);
  84235. triangle.originalOffset = pos;
  84236. _this.triangles.push(triangle);
  84237. };
  84238. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  84239. _this.init(callback);
  84240. });
  84241. });
  84242. };
  84243. QuadraticErrorSimplification.prototype.init = function (callback) {
  84244. var _this = this;
  84245. var triangleInit1 = function (i) {
  84246. var t = _this.triangles[i];
  84247. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  84248. for (var j = 0; j < 3; j++) {
  84249. 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))));
  84250. }
  84251. };
  84252. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  84253. var triangleInit2 = function (i) {
  84254. var t = _this.triangles[i];
  84255. for (var j = 0; j < 3; ++j) {
  84256. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  84257. }
  84258. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  84259. };
  84260. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  84261. callback();
  84262. });
  84263. });
  84264. };
  84265. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  84266. var newTriangles = [];
  84267. var i;
  84268. for (i = 0; i < this.vertices.length; ++i) {
  84269. this.vertices[i].triangleCount = 0;
  84270. }
  84271. var t;
  84272. var j;
  84273. for (i = 0; i < this.triangles.length; ++i) {
  84274. if (!this.triangles[i].deleted) {
  84275. t = this.triangles[i];
  84276. for (j = 0; j < 3; ++j) {
  84277. t.vertices[j].triangleCount = 1;
  84278. }
  84279. newTriangles.push(t);
  84280. }
  84281. }
  84282. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  84283. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  84284. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  84285. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  84286. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  84287. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  84288. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  84289. var vertexCount = 0;
  84290. for (i = 0; i < this.vertices.length; ++i) {
  84291. var vertex = this.vertices[i];
  84292. vertex.id = vertexCount;
  84293. if (vertex.triangleCount) {
  84294. vertex.originalOffsets.forEach(function (originalOffset) {
  84295. if (!normalData) {
  84296. return;
  84297. }
  84298. newPositionData.push(vertex.position.x);
  84299. newPositionData.push(vertex.position.y);
  84300. newPositionData.push(vertex.position.z);
  84301. newNormalData.push(normalData[originalOffset * 3]);
  84302. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  84303. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  84304. if (uvs && uvs.length) {
  84305. newUVsData.push(uvs[(originalOffset * 2)]);
  84306. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  84307. }
  84308. else if (colorsData && colorsData.length) {
  84309. newColorsData.push(colorsData[(originalOffset * 4)]);
  84310. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  84311. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  84312. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  84313. }
  84314. ++vertexCount;
  84315. });
  84316. }
  84317. }
  84318. var startingIndex = this._reconstructedMesh.getTotalIndices();
  84319. var startingVertex = this._reconstructedMesh.getTotalVertices();
  84320. var submeshesArray = this._reconstructedMesh.subMeshes;
  84321. this._reconstructedMesh.subMeshes = [];
  84322. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  84323. var originalIndices = this._mesh.getIndices();
  84324. for (i = 0; i < newTriangles.length; ++i) {
  84325. t = newTriangles[i]; //now get the new referencing point for each vertex
  84326. [0, 1, 2].forEach(function (idx) {
  84327. var id = originalIndices[t.originalOffset + idx];
  84328. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  84329. if (offset < 0)
  84330. offset = 0;
  84331. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  84332. });
  84333. }
  84334. //overwriting the old vertex buffers and indices.
  84335. this._reconstructedMesh.setIndices(newIndicesArray);
  84336. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  84337. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  84338. if (newUVsData.length > 0)
  84339. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  84340. if (newColorsData.length > 0)
  84341. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  84342. //create submesh
  84343. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  84344. if (submeshIndex > 0) {
  84345. this._reconstructedMesh.subMeshes = [];
  84346. submeshesArray.forEach(function (submesh) {
  84347. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  84348. });
  84349. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  84350. }
  84351. };
  84352. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  84353. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  84354. this._reconstructedMesh.material = this._mesh.material;
  84355. this._reconstructedMesh.parent = this._mesh.parent;
  84356. this._reconstructedMesh.isVisible = false;
  84357. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  84358. };
  84359. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  84360. for (var i = 0; i < vertex1.triangleCount; ++i) {
  84361. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  84362. if (t.deleted)
  84363. continue;
  84364. var s = this.references[vertex1.triangleStart + i].vertexId;
  84365. var v1 = t.vertices[(s + 1) % 3];
  84366. var v2 = t.vertices[(s + 2) % 3];
  84367. if ((v1 === vertex2 || v2 === vertex2)) {
  84368. deletedArray[i] = true;
  84369. delTr.push(t);
  84370. continue;
  84371. }
  84372. var d1 = v1.position.subtract(point);
  84373. d1 = d1.normalize();
  84374. var d2 = v2.position.subtract(point);
  84375. d2 = d2.normalize();
  84376. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  84377. return true;
  84378. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  84379. deletedArray[i] = false;
  84380. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  84381. return true;
  84382. }
  84383. return false;
  84384. };
  84385. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  84386. var newDeleted = deletedTriangles;
  84387. for (var i = 0; i < vertex.triangleCount; ++i) {
  84388. var ref = this.references[vertex.triangleStart + i];
  84389. var t = this.triangles[ref.triangleId];
  84390. if (t.deleted)
  84391. continue;
  84392. if (deletedArray[i] && t.deletePending) {
  84393. t.deleted = true;
  84394. newDeleted++;
  84395. continue;
  84396. }
  84397. t.vertices[ref.vertexId] = origVertex;
  84398. t.isDirty = true;
  84399. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  84400. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  84401. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  84402. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  84403. this.references.push(ref);
  84404. }
  84405. return newDeleted;
  84406. };
  84407. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  84408. for (var i = 0; i < this.vertices.length; ++i) {
  84409. var vCount = [];
  84410. var vId = [];
  84411. var v = this.vertices[i];
  84412. var j;
  84413. for (j = 0; j < v.triangleCount; ++j) {
  84414. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  84415. for (var ii = 0; ii < 3; ii++) {
  84416. var ofs = 0;
  84417. var vv = triangle.vertices[ii];
  84418. while (ofs < vCount.length) {
  84419. if (vId[ofs] === vv.id)
  84420. break;
  84421. ++ofs;
  84422. }
  84423. if (ofs === vCount.length) {
  84424. vCount.push(1);
  84425. vId.push(vv.id);
  84426. }
  84427. else {
  84428. vCount[ofs]++;
  84429. }
  84430. }
  84431. }
  84432. for (j = 0; j < vCount.length; ++j) {
  84433. if (vCount[j] === 1) {
  84434. this.vertices[vId[j]].isBorder = true;
  84435. }
  84436. else {
  84437. this.vertices[vId[j]].isBorder = false;
  84438. }
  84439. }
  84440. }
  84441. };
  84442. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  84443. if (identifyBorders === void 0) { identifyBorders = false; }
  84444. var i;
  84445. if (!identifyBorders) {
  84446. var newTrianglesVector = [];
  84447. for (i = 0; i < this.triangles.length; ++i) {
  84448. if (!this.triangles[i].deleted) {
  84449. newTrianglesVector.push(this.triangles[i]);
  84450. }
  84451. }
  84452. this.triangles = newTrianglesVector;
  84453. }
  84454. for (i = 0; i < this.vertices.length; ++i) {
  84455. this.vertices[i].triangleCount = 0;
  84456. this.vertices[i].triangleStart = 0;
  84457. }
  84458. var t;
  84459. var j;
  84460. var v;
  84461. for (i = 0; i < this.triangles.length; ++i) {
  84462. t = this.triangles[i];
  84463. for (j = 0; j < 3; ++j) {
  84464. v = t.vertices[j];
  84465. v.triangleCount++;
  84466. }
  84467. }
  84468. var tStart = 0;
  84469. for (i = 0; i < this.vertices.length; ++i) {
  84470. this.vertices[i].triangleStart = tStart;
  84471. tStart += this.vertices[i].triangleCount;
  84472. this.vertices[i].triangleCount = 0;
  84473. }
  84474. var newReferences = new Array(this.triangles.length * 3);
  84475. for (i = 0; i < this.triangles.length; ++i) {
  84476. t = this.triangles[i];
  84477. for (j = 0; j < 3; ++j) {
  84478. v = t.vertices[j];
  84479. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  84480. v.triangleCount++;
  84481. }
  84482. }
  84483. this.references = newReferences;
  84484. if (identifyBorders) {
  84485. this.identifyBorder();
  84486. }
  84487. };
  84488. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  84489. var x = point.x;
  84490. var y = point.y;
  84491. var z = point.z;
  84492. 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
  84493. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  84494. };
  84495. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  84496. var q = vertex1.q.add(vertex2.q);
  84497. var border = vertex1.isBorder && vertex2.isBorder;
  84498. var error = 0;
  84499. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  84500. if (qDet !== 0 && !border) {
  84501. if (!pointResult) {
  84502. pointResult = BABYLON.Vector3.Zero();
  84503. }
  84504. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  84505. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  84506. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  84507. error = this.vertexError(q, pointResult);
  84508. }
  84509. else {
  84510. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  84511. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  84512. var error1 = this.vertexError(q, vertex1.position);
  84513. var error2 = this.vertexError(q, vertex2.position);
  84514. var error3 = this.vertexError(q, p3);
  84515. error = Math.min(error1, error2, error3);
  84516. if (error === error1) {
  84517. if (pointResult) {
  84518. pointResult.copyFrom(vertex1.position);
  84519. }
  84520. }
  84521. else if (error === error2) {
  84522. if (pointResult) {
  84523. pointResult.copyFrom(vertex2.position);
  84524. }
  84525. }
  84526. else {
  84527. if (pointResult) {
  84528. pointResult.copyFrom(p3);
  84529. }
  84530. }
  84531. }
  84532. return error;
  84533. };
  84534. return QuadraticErrorSimplification;
  84535. }());
  84536. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  84537. })(BABYLON || (BABYLON = {}));
  84538. //# sourceMappingURL=babylon.meshSimplification.js.map
  84539. var BABYLON;
  84540. (function (BABYLON) {
  84541. var MeshLODLevel = /** @class */ (function () {
  84542. function MeshLODLevel(distance, mesh) {
  84543. this.distance = distance;
  84544. this.mesh = mesh;
  84545. }
  84546. return MeshLODLevel;
  84547. }());
  84548. BABYLON.MeshLODLevel = MeshLODLevel;
  84549. })(BABYLON || (BABYLON = {}));
  84550. //# sourceMappingURL=babylon.meshLODLevel.js.map
  84551. var BABYLON;
  84552. (function (BABYLON) {
  84553. /**
  84554. * Defines the root class used to create scene optimization to use with SceneOptimizer
  84555. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84556. */
  84557. var SceneOptimization = /** @class */ (function () {
  84558. /**
  84559. * Creates the SceneOptimization object
  84560. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84561. * @param desc defines the description associated with the optimization
  84562. */
  84563. function SceneOptimization(
  84564. /**
  84565. * Defines the priority of this optimization (0 by default which means first in the list)
  84566. */
  84567. priority) {
  84568. if (priority === void 0) { priority = 0; }
  84569. this.priority = priority;
  84570. }
  84571. /**
  84572. * Gets a string describing the action executed by the current optimization
  84573. * @returns description string
  84574. */
  84575. SceneOptimization.prototype.getDescription = function () {
  84576. return "";
  84577. };
  84578. /**
  84579. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84580. * @param scene defines the current scene where to apply this optimization
  84581. * @param optimizer defines the current optimizer
  84582. * @returns true if everything that can be done was applied
  84583. */
  84584. SceneOptimization.prototype.apply = function (scene, optimizer) {
  84585. return true;
  84586. };
  84587. ;
  84588. return SceneOptimization;
  84589. }());
  84590. BABYLON.SceneOptimization = SceneOptimization;
  84591. /**
  84592. * Defines an optimization used to reduce the size of render target textures
  84593. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84594. */
  84595. var TextureOptimization = /** @class */ (function (_super) {
  84596. __extends(TextureOptimization, _super);
  84597. /**
  84598. * Creates the TextureOptimization object
  84599. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84600. * @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
  84601. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  84602. */
  84603. function TextureOptimization(
  84604. /**
  84605. * Defines the priority of this optimization (0 by default which means first in the list)
  84606. */
  84607. priority,
  84608. /**
  84609. * 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
  84610. */
  84611. maximumSize,
  84612. /**
  84613. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  84614. */
  84615. step) {
  84616. if (priority === void 0) { priority = 0; }
  84617. if (maximumSize === void 0) { maximumSize = 1024; }
  84618. if (step === void 0) { step = 0.5; }
  84619. var _this = _super.call(this, priority) || this;
  84620. _this.priority = priority;
  84621. _this.maximumSize = maximumSize;
  84622. _this.step = step;
  84623. return _this;
  84624. }
  84625. /**
  84626. * Gets a string describing the action executed by the current optimization
  84627. * @returns description string
  84628. */
  84629. TextureOptimization.prototype.getDescription = function () {
  84630. return "Reducing render target texture size to " + this.maximumSize;
  84631. };
  84632. /**
  84633. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84634. * @param scene defines the current scene where to apply this optimization
  84635. * @param optimizer defines the current optimizer
  84636. * @returns true if everything that can be done was applied
  84637. */
  84638. TextureOptimization.prototype.apply = function (scene, optimizer) {
  84639. var allDone = true;
  84640. for (var index = 0; index < scene.textures.length; index++) {
  84641. var texture = scene.textures[index];
  84642. if (!texture.canRescale || texture.getContext) {
  84643. continue;
  84644. }
  84645. var currentSize = texture.getSize();
  84646. var maxDimension = Math.max(currentSize.width, currentSize.height);
  84647. if (maxDimension > this.maximumSize) {
  84648. texture.scale(this.step);
  84649. allDone = false;
  84650. }
  84651. }
  84652. return allDone;
  84653. };
  84654. return TextureOptimization;
  84655. }(SceneOptimization));
  84656. BABYLON.TextureOptimization = TextureOptimization;
  84657. /**
  84658. * Defines an optimization used to increase or decrease the rendering resolution
  84659. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84660. */
  84661. var HardwareScalingOptimization = /** @class */ (function (_super) {
  84662. __extends(HardwareScalingOptimization, _super);
  84663. /**
  84664. * Creates the HardwareScalingOptimization object
  84665. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84666. * @param maximumScale defines the maximum scale to use (2 by default)
  84667. * @param step defines the step to use between two passes (0.5 by default)
  84668. */
  84669. function HardwareScalingOptimization(
  84670. /**
  84671. * Defines the priority of this optimization (0 by default which means first in the list)
  84672. */
  84673. priority,
  84674. /**
  84675. * Defines the maximum scale to use (2 by default)
  84676. */
  84677. maximumScale,
  84678. /**
  84679. * Defines the step to use between two passes (0.5 by default)
  84680. */
  84681. step) {
  84682. if (priority === void 0) { priority = 0; }
  84683. if (maximumScale === void 0) { maximumScale = 2; }
  84684. if (step === void 0) { step = 0.25; }
  84685. var _this = _super.call(this, priority) || this;
  84686. _this.priority = priority;
  84687. _this.maximumScale = maximumScale;
  84688. _this.step = step;
  84689. _this._currentScale = -1;
  84690. _this._directionOffset = 1;
  84691. return _this;
  84692. }
  84693. /**
  84694. * Gets a string describing the action executed by the current optimization
  84695. * @return description string
  84696. */
  84697. HardwareScalingOptimization.prototype.getDescription = function () {
  84698. return "Setting hardware scaling level to " + this._currentScale;
  84699. };
  84700. /**
  84701. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84702. * @param scene defines the current scene where to apply this optimization
  84703. * @param optimizer defines the current optimizer
  84704. * @returns true if everything that can be done was applied
  84705. */
  84706. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  84707. if (this._currentScale === -1) {
  84708. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  84709. if (this._currentScale > this.maximumScale) {
  84710. this._directionOffset = -1;
  84711. }
  84712. }
  84713. this._currentScale += this._directionOffset * this.step;
  84714. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  84715. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  84716. };
  84717. ;
  84718. return HardwareScalingOptimization;
  84719. }(SceneOptimization));
  84720. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  84721. /**
  84722. * Defines an optimization used to remove shadows
  84723. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84724. */
  84725. var ShadowsOptimization = /** @class */ (function (_super) {
  84726. __extends(ShadowsOptimization, _super);
  84727. function ShadowsOptimization() {
  84728. return _super !== null && _super.apply(this, arguments) || this;
  84729. }
  84730. /**
  84731. * Gets a string describing the action executed by the current optimization
  84732. * @return description string
  84733. */
  84734. ShadowsOptimization.prototype.getDescription = function () {
  84735. return "Turning shadows on/off";
  84736. };
  84737. /**
  84738. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84739. * @param scene defines the current scene where to apply this optimization
  84740. * @param optimizer defines the current optimizer
  84741. * @returns true if everything that can be done was applied
  84742. */
  84743. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  84744. scene.shadowsEnabled = optimizer.isInImprovementMode;
  84745. return true;
  84746. };
  84747. ;
  84748. return ShadowsOptimization;
  84749. }(SceneOptimization));
  84750. BABYLON.ShadowsOptimization = ShadowsOptimization;
  84751. /**
  84752. * Defines an optimization used to turn post-processes off
  84753. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84754. */
  84755. var PostProcessesOptimization = /** @class */ (function (_super) {
  84756. __extends(PostProcessesOptimization, _super);
  84757. function PostProcessesOptimization() {
  84758. return _super !== null && _super.apply(this, arguments) || this;
  84759. }
  84760. /**
  84761. * Gets a string describing the action executed by the current optimization
  84762. * @return description string
  84763. */
  84764. PostProcessesOptimization.prototype.getDescription = function () {
  84765. return "Turning post-processes on/off";
  84766. };
  84767. /**
  84768. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84769. * @param scene defines the current scene where to apply this optimization
  84770. * @param optimizer defines the current optimizer
  84771. * @returns true if everything that can be done was applied
  84772. */
  84773. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  84774. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  84775. return true;
  84776. };
  84777. ;
  84778. return PostProcessesOptimization;
  84779. }(SceneOptimization));
  84780. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  84781. /**
  84782. * Defines an optimization used to turn lens flares off
  84783. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84784. */
  84785. var LensFlaresOptimization = /** @class */ (function (_super) {
  84786. __extends(LensFlaresOptimization, _super);
  84787. function LensFlaresOptimization() {
  84788. return _super !== null && _super.apply(this, arguments) || this;
  84789. }
  84790. /**
  84791. * Gets a string describing the action executed by the current optimization
  84792. * @return description string
  84793. */
  84794. LensFlaresOptimization.prototype.getDescription = function () {
  84795. return "Turning lens flares on/off";
  84796. };
  84797. /**
  84798. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84799. * @param scene defines the current scene where to apply this optimization
  84800. * @param optimizer defines the current optimizer
  84801. * @returns true if everything that can be done was applied
  84802. */
  84803. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  84804. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  84805. return true;
  84806. };
  84807. ;
  84808. return LensFlaresOptimization;
  84809. }(SceneOptimization));
  84810. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  84811. /**
  84812. * Defines an optimization based on user defined callback.
  84813. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84814. */
  84815. var CustomOptimization = /** @class */ (function (_super) {
  84816. __extends(CustomOptimization, _super);
  84817. function CustomOptimization() {
  84818. return _super !== null && _super.apply(this, arguments) || this;
  84819. }
  84820. /**
  84821. * Gets a string describing the action executed by the current optimization
  84822. * @returns description string
  84823. */
  84824. CustomOptimization.prototype.getDescription = function () {
  84825. if (this.onGetDescription) {
  84826. return this.onGetDescription();
  84827. }
  84828. return "Running user defined callback";
  84829. };
  84830. /**
  84831. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84832. * @param scene defines the current scene where to apply this optimization
  84833. * @param optimizer defines the current optimizer
  84834. * @returns true if everything that can be done was applied
  84835. */
  84836. CustomOptimization.prototype.apply = function (scene, optimizer) {
  84837. if (this.onApply) {
  84838. return this.onApply(scene, optimizer);
  84839. }
  84840. return true;
  84841. };
  84842. ;
  84843. return CustomOptimization;
  84844. }(SceneOptimization));
  84845. BABYLON.CustomOptimization = CustomOptimization;
  84846. /**
  84847. * Defines an optimization used to turn particles off
  84848. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84849. */
  84850. var ParticlesOptimization = /** @class */ (function (_super) {
  84851. __extends(ParticlesOptimization, _super);
  84852. function ParticlesOptimization() {
  84853. return _super !== null && _super.apply(this, arguments) || this;
  84854. }
  84855. /**
  84856. * Gets a string describing the action executed by the current optimization
  84857. * @return description string
  84858. */
  84859. ParticlesOptimization.prototype.getDescription = function () {
  84860. return "Turning particles on/off";
  84861. };
  84862. /**
  84863. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84864. * @param scene defines the current scene where to apply this optimization
  84865. * @param optimizer defines the current optimizer
  84866. * @returns true if everything that can be done was applied
  84867. */
  84868. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  84869. scene.particlesEnabled = optimizer.isInImprovementMode;
  84870. return true;
  84871. };
  84872. ;
  84873. return ParticlesOptimization;
  84874. }(SceneOptimization));
  84875. BABYLON.ParticlesOptimization = ParticlesOptimization;
  84876. /**
  84877. * Defines an optimization used to turn render targets off
  84878. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84879. */
  84880. var RenderTargetsOptimization = /** @class */ (function (_super) {
  84881. __extends(RenderTargetsOptimization, _super);
  84882. function RenderTargetsOptimization() {
  84883. return _super !== null && _super.apply(this, arguments) || this;
  84884. }
  84885. /**
  84886. * Gets a string describing the action executed by the current optimization
  84887. * @return description string
  84888. */
  84889. RenderTargetsOptimization.prototype.getDescription = function () {
  84890. return "Turning render targets off";
  84891. };
  84892. /**
  84893. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84894. * @param scene defines the current scene where to apply this optimization
  84895. * @param optimizer defines the current optimizer
  84896. * @returns true if everything that can be done was applied
  84897. */
  84898. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  84899. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  84900. return true;
  84901. };
  84902. ;
  84903. return RenderTargetsOptimization;
  84904. }(SceneOptimization));
  84905. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  84906. /**
  84907. * Defines an optimization used to merge meshes with compatible materials
  84908. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84909. */
  84910. var MergeMeshesOptimization = /** @class */ (function (_super) {
  84911. __extends(MergeMeshesOptimization, _super);
  84912. function MergeMeshesOptimization() {
  84913. var _this = _super !== null && _super.apply(this, arguments) || this;
  84914. _this._canBeMerged = function (abstractMesh) {
  84915. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  84916. return false;
  84917. }
  84918. var mesh = abstractMesh;
  84919. if (!mesh.isVisible || !mesh.isEnabled()) {
  84920. return false;
  84921. }
  84922. if (mesh.instances.length > 0) {
  84923. return false;
  84924. }
  84925. if (mesh.skeleton || mesh.hasLODLevels) {
  84926. return false;
  84927. }
  84928. if (mesh.parent) {
  84929. return false;
  84930. }
  84931. return true;
  84932. };
  84933. return _this;
  84934. }
  84935. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  84936. /**
  84937. * Gets or sets a boolean which defines if optimization octree has to be updated
  84938. */
  84939. get: function () {
  84940. return MergeMeshesOptimization._UpdateSelectionTree;
  84941. },
  84942. /**
  84943. * Gets or sets a boolean which defines if optimization octree has to be updated
  84944. */
  84945. set: function (value) {
  84946. MergeMeshesOptimization._UpdateSelectionTree = value;
  84947. },
  84948. enumerable: true,
  84949. configurable: true
  84950. });
  84951. /**
  84952. * Gets a string describing the action executed by the current optimization
  84953. * @return description string
  84954. */
  84955. MergeMeshesOptimization.prototype.getDescription = function () {
  84956. return "Merging similar meshes together";
  84957. };
  84958. /**
  84959. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84960. * @param scene defines the current scene where to apply this optimization
  84961. * @param optimizer defines the current optimizer
  84962. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  84963. * @returns true if everything that can be done was applied
  84964. */
  84965. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  84966. var globalPool = scene.meshes.slice(0);
  84967. var globalLength = globalPool.length;
  84968. for (var index = 0; index < globalLength; index++) {
  84969. var currentPool = new Array();
  84970. var current = globalPool[index];
  84971. // Checks
  84972. if (!this._canBeMerged(current)) {
  84973. continue;
  84974. }
  84975. currentPool.push(current);
  84976. // Find compatible meshes
  84977. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  84978. var otherMesh = globalPool[subIndex];
  84979. if (!this._canBeMerged(otherMesh)) {
  84980. continue;
  84981. }
  84982. if (otherMesh.material !== current.material) {
  84983. continue;
  84984. }
  84985. if (otherMesh.checkCollisions !== current.checkCollisions) {
  84986. continue;
  84987. }
  84988. currentPool.push(otherMesh);
  84989. globalLength--;
  84990. globalPool.splice(subIndex, 1);
  84991. subIndex--;
  84992. }
  84993. if (currentPool.length < 2) {
  84994. continue;
  84995. }
  84996. // Merge meshes
  84997. BABYLON.Mesh.MergeMeshes(currentPool);
  84998. }
  84999. if (updateSelectionTree != undefined) {
  85000. if (updateSelectionTree) {
  85001. scene.createOrUpdateSelectionOctree();
  85002. }
  85003. }
  85004. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  85005. scene.createOrUpdateSelectionOctree();
  85006. }
  85007. return true;
  85008. };
  85009. ;
  85010. MergeMeshesOptimization._UpdateSelectionTree = false;
  85011. return MergeMeshesOptimization;
  85012. }(SceneOptimization));
  85013. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  85014. /**
  85015. * Defines a list of options used by SceneOptimizer
  85016. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85017. */
  85018. var SceneOptimizerOptions = /** @class */ (function () {
  85019. /**
  85020. * Creates a new list of options used by SceneOptimizer
  85021. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  85022. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  85023. */
  85024. function SceneOptimizerOptions(
  85025. /**
  85026. * Defines the target frame rate to reach (60 by default)
  85027. */
  85028. targetFrameRate,
  85029. /**
  85030. * Defines the interval between two checkes (2000ms by default)
  85031. */
  85032. trackerDuration) {
  85033. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  85034. if (trackerDuration === void 0) { trackerDuration = 2000; }
  85035. this.targetFrameRate = targetFrameRate;
  85036. this.trackerDuration = trackerDuration;
  85037. /**
  85038. * Gets the list of optimizations to apply
  85039. */
  85040. this.optimizations = new Array();
  85041. }
  85042. /**
  85043. * Add a new optimization
  85044. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  85045. * @returns the current SceneOptimizerOptions
  85046. */
  85047. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  85048. this.optimizations.push(optimization);
  85049. return this;
  85050. };
  85051. /**
  85052. * Add a new custom optimization
  85053. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  85054. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  85055. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85056. * @returns the current SceneOptimizerOptions
  85057. */
  85058. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  85059. if (priority === void 0) { priority = 0; }
  85060. var optimization = new CustomOptimization(priority);
  85061. optimization.onApply = onApply;
  85062. optimization.onGetDescription = onGetDescription;
  85063. this.optimizations.push(optimization);
  85064. return this;
  85065. };
  85066. /**
  85067. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  85068. * @param targetFrameRate defines the target frame rate (60 by default)
  85069. * @returns a SceneOptimizerOptions object
  85070. */
  85071. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  85072. var result = new SceneOptimizerOptions(targetFrameRate);
  85073. var priority = 0;
  85074. result.addOptimization(new MergeMeshesOptimization(priority));
  85075. result.addOptimization(new ShadowsOptimization(priority));
  85076. result.addOptimization(new LensFlaresOptimization(priority));
  85077. // Next priority
  85078. priority++;
  85079. result.addOptimization(new PostProcessesOptimization(priority));
  85080. result.addOptimization(new ParticlesOptimization(priority));
  85081. // Next priority
  85082. priority++;
  85083. result.addOptimization(new TextureOptimization(priority, 1024));
  85084. return result;
  85085. };
  85086. /**
  85087. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  85088. * @param targetFrameRate defines the target frame rate (60 by default)
  85089. * @returns a SceneOptimizerOptions object
  85090. */
  85091. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  85092. var result = new SceneOptimizerOptions(targetFrameRate);
  85093. var priority = 0;
  85094. result.addOptimization(new MergeMeshesOptimization(priority));
  85095. result.addOptimization(new ShadowsOptimization(priority));
  85096. result.addOptimization(new LensFlaresOptimization(priority));
  85097. // Next priority
  85098. priority++;
  85099. result.addOptimization(new PostProcessesOptimization(priority));
  85100. result.addOptimization(new ParticlesOptimization(priority));
  85101. // Next priority
  85102. priority++;
  85103. result.addOptimization(new TextureOptimization(priority, 512));
  85104. // Next priority
  85105. priority++;
  85106. result.addOptimization(new RenderTargetsOptimization(priority));
  85107. // Next priority
  85108. priority++;
  85109. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  85110. return result;
  85111. };
  85112. /**
  85113. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  85114. * @param targetFrameRate defines the target frame rate (60 by default)
  85115. * @returns a SceneOptimizerOptions object
  85116. */
  85117. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  85118. var result = new SceneOptimizerOptions(targetFrameRate);
  85119. var priority = 0;
  85120. result.addOptimization(new MergeMeshesOptimization(priority));
  85121. result.addOptimization(new ShadowsOptimization(priority));
  85122. result.addOptimization(new LensFlaresOptimization(priority));
  85123. // Next priority
  85124. priority++;
  85125. result.addOptimization(new PostProcessesOptimization(priority));
  85126. result.addOptimization(new ParticlesOptimization(priority));
  85127. // Next priority
  85128. priority++;
  85129. result.addOptimization(new TextureOptimization(priority, 256));
  85130. // Next priority
  85131. priority++;
  85132. result.addOptimization(new RenderTargetsOptimization(priority));
  85133. // Next priority
  85134. priority++;
  85135. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  85136. return result;
  85137. };
  85138. return SceneOptimizerOptions;
  85139. }());
  85140. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  85141. /**
  85142. * Class used to run optimizations in order to reach a target frame rate
  85143. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85144. */
  85145. var SceneOptimizer = /** @class */ (function () {
  85146. /**
  85147. * Creates a new SceneOptimizer
  85148. * @param scene defines the scene to work on
  85149. * @param options defines the options to use with the SceneOptimizer
  85150. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  85151. * @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)
  85152. */
  85153. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  85154. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  85155. if (improvementMode === void 0) { improvementMode = false; }
  85156. var _this = this;
  85157. this._isRunning = false;
  85158. this._currentPriorityLevel = 0;
  85159. this._targetFrameRate = 60;
  85160. this._trackerDuration = 2000;
  85161. this._currentFrameRate = 0;
  85162. this._improvementMode = false;
  85163. /**
  85164. * Defines an observable called when the optimizer reaches the target frame rate
  85165. */
  85166. this.onSuccessObservable = new BABYLON.Observable();
  85167. /**
  85168. * Defines an observable called when the optimizer enables an optimization
  85169. */
  85170. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  85171. /**
  85172. * Defines an observable called when the optimizer is not able to reach the target frame rate
  85173. */
  85174. this.onFailureObservable = new BABYLON.Observable();
  85175. if (!options) {
  85176. this._options = new SceneOptimizerOptions();
  85177. }
  85178. else {
  85179. this._options = options;
  85180. }
  85181. if (this._options.targetFrameRate) {
  85182. this._targetFrameRate = this._options.targetFrameRate;
  85183. }
  85184. if (this._options.trackerDuration) {
  85185. this._trackerDuration = this._options.trackerDuration;
  85186. }
  85187. if (autoGeneratePriorities) {
  85188. var priority = 0;
  85189. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  85190. var optim = _a[_i];
  85191. optim.priority = priority++;
  85192. }
  85193. }
  85194. this._improvementMode = improvementMode;
  85195. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85196. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  85197. _this._sceneDisposeObserver = null;
  85198. _this.dispose();
  85199. });
  85200. }
  85201. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  85202. /**
  85203. * Gets a boolean indicating if the optimizer is in improvement mode
  85204. */
  85205. get: function () {
  85206. return this._improvementMode;
  85207. },
  85208. enumerable: true,
  85209. configurable: true
  85210. });
  85211. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  85212. /**
  85213. * Gets the current priority level (0 at start)
  85214. */
  85215. get: function () {
  85216. return this._currentPriorityLevel;
  85217. },
  85218. enumerable: true,
  85219. configurable: true
  85220. });
  85221. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  85222. /**
  85223. * Gets the current frame rate checked by the SceneOptimizer
  85224. */
  85225. get: function () {
  85226. return this._currentFrameRate;
  85227. },
  85228. enumerable: true,
  85229. configurable: true
  85230. });
  85231. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  85232. /**
  85233. * Gets or sets the current target frame rate (60 by default)
  85234. */
  85235. get: function () {
  85236. return this._targetFrameRate;
  85237. },
  85238. /**
  85239. * Gets or sets the current target frame rate (60 by default)
  85240. */
  85241. set: function (value) {
  85242. this._targetFrameRate = value;
  85243. },
  85244. enumerable: true,
  85245. configurable: true
  85246. });
  85247. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  85248. /**
  85249. * Gets or sets the current interval between two checks (every 2000ms by default)
  85250. */
  85251. get: function () {
  85252. return this._trackerDuration;
  85253. },
  85254. /**
  85255. * Gets or sets the current interval between two checks (every 2000ms by default)
  85256. */
  85257. set: function (value) {
  85258. this._trackerDuration = value;
  85259. },
  85260. enumerable: true,
  85261. configurable: true
  85262. });
  85263. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  85264. /**
  85265. * Gets the list of active optimizations
  85266. */
  85267. get: function () {
  85268. return this._options.optimizations;
  85269. },
  85270. enumerable: true,
  85271. configurable: true
  85272. });
  85273. /**
  85274. * Stops the current optimizer
  85275. */
  85276. SceneOptimizer.prototype.stop = function () {
  85277. this._isRunning = false;
  85278. };
  85279. /**
  85280. * Reset the optimizer to initial step (current priority level = 0)
  85281. */
  85282. SceneOptimizer.prototype.reset = function () {
  85283. this._currentPriorityLevel = 0;
  85284. };
  85285. /**
  85286. * Start the optimizer. By default it will try to reach a specific framerate
  85287. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  85288. */
  85289. SceneOptimizer.prototype.start = function () {
  85290. var _this = this;
  85291. if (this._isRunning) {
  85292. return;
  85293. }
  85294. this._isRunning = true;
  85295. // Let's wait for the scene to be ready before running our check
  85296. this._scene.executeWhenReady(function () {
  85297. setTimeout(function () {
  85298. _this._checkCurrentState();
  85299. }, _this._trackerDuration);
  85300. });
  85301. };
  85302. SceneOptimizer.prototype._checkCurrentState = function () {
  85303. var _this = this;
  85304. if (!this._isRunning) {
  85305. return;
  85306. }
  85307. var scene = this._scene;
  85308. var options = this._options;
  85309. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  85310. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  85311. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  85312. this._isRunning = false;
  85313. this.onSuccessObservable.notifyObservers(this);
  85314. return;
  85315. }
  85316. // Apply current level of optimizations
  85317. var allDone = true;
  85318. var noOptimizationApplied = true;
  85319. for (var index = 0; index < options.optimizations.length; index++) {
  85320. var optimization = options.optimizations[index];
  85321. if (optimization.priority === this._currentPriorityLevel) {
  85322. noOptimizationApplied = false;
  85323. allDone = allDone && optimization.apply(scene, this);
  85324. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  85325. }
  85326. }
  85327. // If no optimization was applied, this is a failure :(
  85328. if (noOptimizationApplied) {
  85329. this._isRunning = false;
  85330. this.onFailureObservable.notifyObservers(this);
  85331. return;
  85332. }
  85333. // If all optimizations were done, move to next level
  85334. if (allDone) {
  85335. this._currentPriorityLevel++;
  85336. }
  85337. // Let's the system running for a specific amount of time before checking FPS
  85338. scene.executeWhenReady(function () {
  85339. setTimeout(function () {
  85340. _this._checkCurrentState();
  85341. }, _this._trackerDuration);
  85342. });
  85343. };
  85344. /**
  85345. * Release all resources
  85346. */
  85347. SceneOptimizer.prototype.dispose = function () {
  85348. this.stop();
  85349. this.onSuccessObservable.clear();
  85350. this.onFailureObservable.clear();
  85351. this.onNewOptimizationAppliedObservable.clear();
  85352. if (this._sceneDisposeObserver) {
  85353. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  85354. }
  85355. };
  85356. /**
  85357. * Helper function to create a SceneOptimizer with one single line of code
  85358. * @param scene defines the scene to work on
  85359. * @param options defines the options to use with the SceneOptimizer
  85360. * @param onSuccess defines a callback to call on success
  85361. * @param onFailure defines a callback to call on failure
  85362. * @returns the new SceneOptimizer object
  85363. */
  85364. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  85365. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  85366. if (onSuccess) {
  85367. optimizer.onSuccessObservable.add(function () {
  85368. onSuccess();
  85369. });
  85370. }
  85371. if (onFailure) {
  85372. optimizer.onFailureObservable.add(function () {
  85373. onFailure();
  85374. });
  85375. }
  85376. optimizer.start();
  85377. return optimizer;
  85378. };
  85379. return SceneOptimizer;
  85380. }());
  85381. BABYLON.SceneOptimizer = SceneOptimizer;
  85382. })(BABYLON || (BABYLON = {}));
  85383. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  85384. var BABYLON;
  85385. (function (BABYLON) {
  85386. var OutlineRenderer = /** @class */ (function () {
  85387. function OutlineRenderer(scene) {
  85388. this.zOffset = 1;
  85389. this._scene = scene;
  85390. }
  85391. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  85392. var _this = this;
  85393. if (useOverlay === void 0) { useOverlay = false; }
  85394. var scene = this._scene;
  85395. var engine = this._scene.getEngine();
  85396. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  85397. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  85398. return;
  85399. }
  85400. var mesh = subMesh.getRenderingMesh();
  85401. var material = subMesh.getMaterial();
  85402. if (!material || !scene.activeCamera) {
  85403. return;
  85404. }
  85405. engine.enableEffect(this._effect);
  85406. // Logarithmic depth
  85407. if (material.useLogarithmicDepth) {
  85408. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  85409. }
  85410. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  85411. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  85412. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  85413. // Bones
  85414. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  85415. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  85416. }
  85417. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  85418. // Alpha test
  85419. if (material && material.needAlphaTesting()) {
  85420. var alphaTexture = material.getAlphaTestTexture();
  85421. if (alphaTexture) {
  85422. this._effect.setTexture("diffuseSampler", alphaTexture);
  85423. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  85424. }
  85425. }
  85426. engine.setZOffset(-this.zOffset);
  85427. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  85428. engine.setZOffset(0);
  85429. };
  85430. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  85431. var defines = [];
  85432. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  85433. var mesh = subMesh.getMesh();
  85434. var material = subMesh.getMaterial();
  85435. if (material) {
  85436. // Alpha test
  85437. if (material.needAlphaTesting()) {
  85438. defines.push("#define ALPHATEST");
  85439. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85440. attribs.push(BABYLON.VertexBuffer.UVKind);
  85441. defines.push("#define UV1");
  85442. }
  85443. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  85444. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  85445. defines.push("#define UV2");
  85446. }
  85447. }
  85448. //Logarithmic depth
  85449. if (material.useLogarithmicDepth) {
  85450. defines.push("#define LOGARITHMICDEPTH");
  85451. }
  85452. }
  85453. // Bones
  85454. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  85455. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  85456. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  85457. if (mesh.numBoneInfluencers > 4) {
  85458. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  85459. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  85460. }
  85461. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  85462. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  85463. }
  85464. else {
  85465. defines.push("#define NUM_BONE_INFLUENCERS 0");
  85466. }
  85467. // Instances
  85468. if (useInstances) {
  85469. defines.push("#define INSTANCES");
  85470. attribs.push("world0");
  85471. attribs.push("world1");
  85472. attribs.push("world2");
  85473. attribs.push("world3");
  85474. }
  85475. // Get correct effect
  85476. var join = defines.join("\n");
  85477. if (this._cachedDefines !== join) {
  85478. this._cachedDefines = join;
  85479. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  85480. }
  85481. return this._effect.isReady();
  85482. };
  85483. return OutlineRenderer;
  85484. }());
  85485. BABYLON.OutlineRenderer = OutlineRenderer;
  85486. })(BABYLON || (BABYLON = {}));
  85487. //# sourceMappingURL=babylon.outlineRenderer.js.map
  85488. var BABYLON;
  85489. (function (BABYLON) {
  85490. var FaceAdjacencies = /** @class */ (function () {
  85491. function FaceAdjacencies() {
  85492. this.edges = new Array();
  85493. this.edgesConnectedCount = 0;
  85494. }
  85495. return FaceAdjacencies;
  85496. }());
  85497. var EdgesRenderer = /** @class */ (function () {
  85498. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  85499. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  85500. if (epsilon === void 0) { epsilon = 0.95; }
  85501. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  85502. this.edgesWidthScalerForOrthographic = 1000.0;
  85503. this.edgesWidthScalerForPerspective = 50.0;
  85504. this._linesPositions = new Array();
  85505. this._linesNormals = new Array();
  85506. this._linesIndices = new Array();
  85507. this._buffers = {};
  85508. this._checkVerticesInsteadOfIndices = false;
  85509. this._source = source;
  85510. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  85511. this._epsilon = epsilon;
  85512. this._prepareRessources();
  85513. this._generateEdgesLines();
  85514. }
  85515. EdgesRenderer.prototype._prepareRessources = function () {
  85516. if (this._lineShader) {
  85517. return;
  85518. }
  85519. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  85520. attributes: ["position", "normal"],
  85521. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  85522. });
  85523. this._lineShader.disableDepthWrite = true;
  85524. this._lineShader.backFaceCulling = false;
  85525. };
  85526. EdgesRenderer.prototype._rebuild = function () {
  85527. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  85528. if (buffer) {
  85529. buffer._rebuild();
  85530. }
  85531. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  85532. if (buffer) {
  85533. buffer._rebuild();
  85534. }
  85535. var scene = this._source.getScene();
  85536. var engine = scene.getEngine();
  85537. this._ib = engine.createIndexBuffer(this._linesIndices);
  85538. };
  85539. EdgesRenderer.prototype.dispose = function () {
  85540. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  85541. if (buffer) {
  85542. buffer.dispose();
  85543. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  85544. }
  85545. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  85546. if (buffer) {
  85547. buffer.dispose();
  85548. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  85549. }
  85550. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  85551. this._lineShader.dispose();
  85552. };
  85553. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  85554. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  85555. return 0;
  85556. }
  85557. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  85558. return 1;
  85559. }
  85560. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  85561. return 2;
  85562. }
  85563. return -1;
  85564. };
  85565. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  85566. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  85567. return 0;
  85568. }
  85569. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  85570. return 1;
  85571. }
  85572. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  85573. return 2;
  85574. }
  85575. return -1;
  85576. };
  85577. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  85578. var needToCreateLine;
  85579. if (edge === undefined) {
  85580. needToCreateLine = true;
  85581. }
  85582. else {
  85583. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  85584. needToCreateLine = dotProduct < this._epsilon;
  85585. }
  85586. if (needToCreateLine) {
  85587. var offset = this._linesPositions.length / 3;
  85588. var normal = p0.subtract(p1);
  85589. normal.normalize();
  85590. // Positions
  85591. this._linesPositions.push(p0.x);
  85592. this._linesPositions.push(p0.y);
  85593. this._linesPositions.push(p0.z);
  85594. this._linesPositions.push(p0.x);
  85595. this._linesPositions.push(p0.y);
  85596. this._linesPositions.push(p0.z);
  85597. this._linesPositions.push(p1.x);
  85598. this._linesPositions.push(p1.y);
  85599. this._linesPositions.push(p1.z);
  85600. this._linesPositions.push(p1.x);
  85601. this._linesPositions.push(p1.y);
  85602. this._linesPositions.push(p1.z);
  85603. // Normals
  85604. this._linesNormals.push(p1.x);
  85605. this._linesNormals.push(p1.y);
  85606. this._linesNormals.push(p1.z);
  85607. this._linesNormals.push(-1);
  85608. this._linesNormals.push(p1.x);
  85609. this._linesNormals.push(p1.y);
  85610. this._linesNormals.push(p1.z);
  85611. this._linesNormals.push(1);
  85612. this._linesNormals.push(p0.x);
  85613. this._linesNormals.push(p0.y);
  85614. this._linesNormals.push(p0.z);
  85615. this._linesNormals.push(-1);
  85616. this._linesNormals.push(p0.x);
  85617. this._linesNormals.push(p0.y);
  85618. this._linesNormals.push(p0.z);
  85619. this._linesNormals.push(1);
  85620. // Indices
  85621. this._linesIndices.push(offset);
  85622. this._linesIndices.push(offset + 1);
  85623. this._linesIndices.push(offset + 2);
  85624. this._linesIndices.push(offset);
  85625. this._linesIndices.push(offset + 2);
  85626. this._linesIndices.push(offset + 3);
  85627. }
  85628. };
  85629. EdgesRenderer.prototype._generateEdgesLines = function () {
  85630. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  85631. var indices = this._source.getIndices();
  85632. if (!indices || !positions) {
  85633. return;
  85634. }
  85635. // First let's find adjacencies
  85636. var adjacencies = new Array();
  85637. var faceNormals = new Array();
  85638. var index;
  85639. var faceAdjacencies;
  85640. // Prepare faces
  85641. for (index = 0; index < indices.length; index += 3) {
  85642. faceAdjacencies = new FaceAdjacencies();
  85643. var p0Index = indices[index];
  85644. var p1Index = indices[index + 1];
  85645. var p2Index = indices[index + 2];
  85646. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  85647. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  85648. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  85649. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  85650. faceNormal.normalize();
  85651. faceNormals.push(faceNormal);
  85652. adjacencies.push(faceAdjacencies);
  85653. }
  85654. // Scan
  85655. for (index = 0; index < adjacencies.length; index++) {
  85656. faceAdjacencies = adjacencies[index];
  85657. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  85658. var otherFaceAdjacencies = adjacencies[otherIndex];
  85659. if (faceAdjacencies.edgesConnectedCount === 3) {
  85660. break;
  85661. }
  85662. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  85663. continue;
  85664. }
  85665. var otherP0 = indices[otherIndex * 3];
  85666. var otherP1 = indices[otherIndex * 3 + 1];
  85667. var otherP2 = indices[otherIndex * 3 + 2];
  85668. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  85669. var otherEdgeIndex = 0;
  85670. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  85671. continue;
  85672. }
  85673. switch (edgeIndex) {
  85674. case 0:
  85675. if (this._checkVerticesInsteadOfIndices) {
  85676. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  85677. }
  85678. else {
  85679. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  85680. }
  85681. break;
  85682. case 1:
  85683. if (this._checkVerticesInsteadOfIndices) {
  85684. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  85685. }
  85686. else {
  85687. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  85688. }
  85689. break;
  85690. case 2:
  85691. if (this._checkVerticesInsteadOfIndices) {
  85692. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  85693. }
  85694. else {
  85695. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  85696. }
  85697. break;
  85698. }
  85699. if (otherEdgeIndex === -1) {
  85700. continue;
  85701. }
  85702. faceAdjacencies.edges[edgeIndex] = otherIndex;
  85703. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  85704. faceAdjacencies.edgesConnectedCount++;
  85705. otherFaceAdjacencies.edgesConnectedCount++;
  85706. if (faceAdjacencies.edgesConnectedCount === 3) {
  85707. break;
  85708. }
  85709. }
  85710. }
  85711. }
  85712. // Create lines
  85713. for (index = 0; index < adjacencies.length; index++) {
  85714. // 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
  85715. var current = adjacencies[index];
  85716. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  85717. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  85718. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  85719. }
  85720. // Merge into a single mesh
  85721. var engine = this._source.getScene().getEngine();
  85722. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  85723. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  85724. this._ib = engine.createIndexBuffer(this._linesIndices);
  85725. this._indicesCount = this._linesIndices.length;
  85726. };
  85727. EdgesRenderer.prototype.render = function () {
  85728. var scene = this._source.getScene();
  85729. if (!this._lineShader.isReady() || !scene.activeCamera) {
  85730. return;
  85731. }
  85732. var engine = scene.getEngine();
  85733. this._lineShader._preBind();
  85734. // VBOs
  85735. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  85736. scene.resetCachedMaterial();
  85737. this._lineShader.setColor4("color", this._source.edgesColor);
  85738. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  85739. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  85740. }
  85741. else {
  85742. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  85743. }
  85744. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  85745. this._lineShader.bind(this._source.getWorldMatrix());
  85746. // Draw order
  85747. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  85748. this._lineShader.unbind();
  85749. engine.setDepthWrite(true);
  85750. };
  85751. return EdgesRenderer;
  85752. }());
  85753. BABYLON.EdgesRenderer = EdgesRenderer;
  85754. })(BABYLON || (BABYLON = {}));
  85755. //# sourceMappingURL=babylon.edgesRenderer.js.map
  85756. var __assign = (this && this.__assign) || Object.assign || function(t) {
  85757. for (var s, i = 1, n = arguments.length; i < n; i++) {
  85758. s = arguments[i];
  85759. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  85760. t[p] = s[p];
  85761. }
  85762. return t;
  85763. };
  85764. var BABYLON;
  85765. (function (BABYLON) {
  85766. /**
  85767. * The effect layer Helps adding post process effect blended with the main pass.
  85768. *
  85769. * This can be for instance use to generate glow or higlight effects on the scene.
  85770. *
  85771. * The effect layer class can not be used directly and is intented to inherited from to be
  85772. * customized per effects.
  85773. */
  85774. var EffectLayer = /** @class */ (function () {
  85775. /**
  85776. * Instantiates a new effect Layer and references it in the scene.
  85777. * @param name The name of the layer
  85778. * @param scene The scene to use the layer in
  85779. */
  85780. function EffectLayer(
  85781. /** The Friendly of the effect in the scene */
  85782. name, scene) {
  85783. this.name = name;
  85784. this._vertexBuffers = {};
  85785. this._maxSize = 0;
  85786. this._mainTextureDesiredSize = { width: 0, height: 0 };
  85787. this._shouldRender = true;
  85788. this._postProcesses = [];
  85789. this._textures = [];
  85790. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  85791. /**
  85792. * The clear color of the texture used to generate the glow map.
  85793. */
  85794. this.neutralColor = new BABYLON.Color4();
  85795. /**
  85796. * Specifies wether the highlight layer is enabled or not.
  85797. */
  85798. this.isEnabled = true;
  85799. /**
  85800. * An event triggered when the effect layer has been disposed.
  85801. */
  85802. this.onDisposeObservable = new BABYLON.Observable();
  85803. /**
  85804. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  85805. */
  85806. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  85807. /**
  85808. * An event triggered when the generated texture is being merged in the scene.
  85809. */
  85810. this.onBeforeComposeObservable = new BABYLON.Observable();
  85811. /**
  85812. * An event triggered when the generated texture has been merged in the scene.
  85813. */
  85814. this.onAfterComposeObservable = new BABYLON.Observable();
  85815. /**
  85816. * An event triggered when the efffect layer changes its size.
  85817. */
  85818. this.onSizeChangedObservable = new BABYLON.Observable();
  85819. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85820. this._engine = scene.getEngine();
  85821. this._maxSize = this._engine.getCaps().maxTextureSize;
  85822. this._scene.effectLayers.push(this);
  85823. // Generate Buffers
  85824. this._generateIndexBuffer();
  85825. this._genrateVertexBuffer();
  85826. }
  85827. Object.defineProperty(EffectLayer.prototype, "camera", {
  85828. /**
  85829. * Gets the camera attached to the layer.
  85830. */
  85831. get: function () {
  85832. return this._effectLayerOptions.camera;
  85833. },
  85834. enumerable: true,
  85835. configurable: true
  85836. });
  85837. /**
  85838. * Initializes the effect layer with the required options.
  85839. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  85840. */
  85841. EffectLayer.prototype._init = function (options) {
  85842. // Adapt options
  85843. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  85844. this._setMainTextureSize();
  85845. this._createMainTexture();
  85846. this._createTextureAndPostProcesses();
  85847. this._mergeEffect = this._createMergeEffect();
  85848. };
  85849. /**
  85850. * Generates the index buffer of the full screen quad blending to the main canvas.
  85851. */
  85852. EffectLayer.prototype._generateIndexBuffer = function () {
  85853. // Indices
  85854. var indices = [];
  85855. indices.push(0);
  85856. indices.push(1);
  85857. indices.push(2);
  85858. indices.push(0);
  85859. indices.push(2);
  85860. indices.push(3);
  85861. this._indexBuffer = this._engine.createIndexBuffer(indices);
  85862. };
  85863. /**
  85864. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  85865. */
  85866. EffectLayer.prototype._genrateVertexBuffer = function () {
  85867. // VBO
  85868. var vertices = [];
  85869. vertices.push(1, 1);
  85870. vertices.push(-1, 1);
  85871. vertices.push(-1, -1);
  85872. vertices.push(1, -1);
  85873. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  85874. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  85875. };
  85876. /**
  85877. * Sets the main texture desired size which is the closest power of two
  85878. * of the engine canvas size.
  85879. */
  85880. EffectLayer.prototype._setMainTextureSize = function () {
  85881. if (this._effectLayerOptions.mainTextureFixedSize) {
  85882. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  85883. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  85884. }
  85885. else {
  85886. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  85887. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  85888. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  85889. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  85890. }
  85891. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  85892. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  85893. };
  85894. /**
  85895. * Creates the main texture for the effect layer.
  85896. */
  85897. EffectLayer.prototype._createMainTexture = function () {
  85898. var _this = this;
  85899. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  85900. width: this._mainTextureDesiredSize.width,
  85901. height: this._mainTextureDesiredSize.height
  85902. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  85903. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  85904. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85905. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85906. this._mainTexture.anisotropicFilteringLevel = 1;
  85907. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85908. this._mainTexture.renderParticles = false;
  85909. this._mainTexture.renderList = null;
  85910. this._mainTexture.ignoreCameraViewport = true;
  85911. // Custom render function
  85912. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  85913. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  85914. var index;
  85915. var engine = _this._scene.getEngine();
  85916. if (depthOnlySubMeshes.length) {
  85917. engine.setColorWrite(false);
  85918. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  85919. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  85920. }
  85921. engine.setColorWrite(true);
  85922. }
  85923. for (index = 0; index < opaqueSubMeshes.length; index++) {
  85924. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  85925. }
  85926. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  85927. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  85928. }
  85929. for (index = 0; index < transparentSubMeshes.length; index++) {
  85930. _this._renderSubMesh(transparentSubMeshes.data[index]);
  85931. }
  85932. };
  85933. this._mainTexture.onClearObservable.add(function (engine) {
  85934. engine.clear(_this.neutralColor, true, true, true);
  85935. });
  85936. };
  85937. /**
  85938. * Checks for the readiness of the element composing the layer.
  85939. * @param subMesh the mesh to check for
  85940. * @param useInstances specify wether or not to use instances to render the mesh
  85941. * @param emissiveTexture the associated emissive texture used to generate the glow
  85942. * @return true if ready otherwise, false
  85943. */
  85944. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  85945. var material = subMesh.getMaterial();
  85946. if (!material) {
  85947. return false;
  85948. }
  85949. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  85950. return false;
  85951. }
  85952. var defines = [];
  85953. var attribs = [BABYLON.VertexBuffer.PositionKind];
  85954. var mesh = subMesh.getMesh();
  85955. var uv1 = false;
  85956. var uv2 = false;
  85957. // Alpha test
  85958. if (material && material.needAlphaTesting()) {
  85959. var alphaTexture = material.getAlphaTestTexture();
  85960. if (alphaTexture) {
  85961. defines.push("#define ALPHATEST");
  85962. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  85963. alphaTexture.coordinatesIndex === 1) {
  85964. defines.push("#define DIFFUSEUV2");
  85965. uv2 = true;
  85966. }
  85967. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85968. defines.push("#define DIFFUSEUV1");
  85969. uv1 = true;
  85970. }
  85971. }
  85972. }
  85973. // Emissive
  85974. if (emissiveTexture) {
  85975. defines.push("#define EMISSIVE");
  85976. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  85977. emissiveTexture.coordinatesIndex === 1) {
  85978. defines.push("#define EMISSIVEUV2");
  85979. uv2 = true;
  85980. }
  85981. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85982. defines.push("#define EMISSIVEUV1");
  85983. uv1 = true;
  85984. }
  85985. }
  85986. if (uv1) {
  85987. attribs.push(BABYLON.VertexBuffer.UVKind);
  85988. defines.push("#define UV1");
  85989. }
  85990. if (uv2) {
  85991. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  85992. defines.push("#define UV2");
  85993. }
  85994. // Bones
  85995. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  85996. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  85997. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  85998. if (mesh.numBoneInfluencers > 4) {
  85999. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  86000. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  86001. }
  86002. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  86003. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  86004. }
  86005. else {
  86006. defines.push("#define NUM_BONE_INFLUENCERS 0");
  86007. }
  86008. // Instances
  86009. if (useInstances) {
  86010. defines.push("#define INSTANCES");
  86011. attribs.push("world0");
  86012. attribs.push("world1");
  86013. attribs.push("world2");
  86014. attribs.push("world3");
  86015. }
  86016. // Get correct effect
  86017. var join = defines.join("\n");
  86018. if (this._cachedDefines !== join) {
  86019. this._cachedDefines = join;
  86020. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  86021. }
  86022. return this._effectLayerMapGenerationEffect.isReady();
  86023. };
  86024. /**
  86025. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  86026. */
  86027. EffectLayer.prototype.render = function () {
  86028. var currentEffect = this._mergeEffect;
  86029. // Check
  86030. if (!currentEffect.isReady())
  86031. return;
  86032. for (var i = 0; i < this._postProcesses.length; i++) {
  86033. if (!this._postProcesses[i].isReady()) {
  86034. return;
  86035. }
  86036. }
  86037. var engine = this._scene.getEngine();
  86038. this.onBeforeComposeObservable.notifyObservers(this);
  86039. // Render
  86040. engine.enableEffect(currentEffect);
  86041. engine.setState(false);
  86042. // VBOs
  86043. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  86044. // Cache
  86045. var previousAlphaMode = engine.getAlphaMode();
  86046. // Go Blend.
  86047. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  86048. // Blends the map on the main canvas.
  86049. this._internalRender(currentEffect);
  86050. // Restore Alpha
  86051. engine.setAlphaMode(previousAlphaMode);
  86052. this.onAfterComposeObservable.notifyObservers(this);
  86053. // Handle size changes.
  86054. var size = this._mainTexture.getSize();
  86055. this._setMainTextureSize();
  86056. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  86057. // Recreate RTT and post processes on size change.
  86058. this.onSizeChangedObservable.notifyObservers(this);
  86059. this._disposeTextureAndPostProcesses();
  86060. this._createMainTexture();
  86061. this._createTextureAndPostProcesses();
  86062. }
  86063. };
  86064. /**
  86065. * Determine if a given mesh will be used in the current effect.
  86066. * @param mesh mesh to test
  86067. * @returns true if the mesh will be used
  86068. */
  86069. EffectLayer.prototype.hasMesh = function (mesh) {
  86070. return true;
  86071. };
  86072. /**
  86073. * Returns true if the layer contains information to display, otherwise false.
  86074. * @returns true if the glow layer should be rendered
  86075. */
  86076. EffectLayer.prototype.shouldRender = function () {
  86077. return this.isEnabled && this._shouldRender;
  86078. };
  86079. /**
  86080. * Returns true if the mesh should render, otherwise false.
  86081. * @param mesh The mesh to render
  86082. * @returns true if it should render otherwise false
  86083. */
  86084. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  86085. return true;
  86086. };
  86087. /**
  86088. * Returns true if the mesh should render, otherwise false.
  86089. * @param mesh The mesh to render
  86090. * @returns true if it should render otherwise false
  86091. */
  86092. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  86093. return true;
  86094. };
  86095. /**
  86096. * Renders the submesh passed in parameter to the generation map.
  86097. */
  86098. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  86099. var _this = this;
  86100. if (!this.shouldRender()) {
  86101. return;
  86102. }
  86103. var material = subMesh.getMaterial();
  86104. var mesh = subMesh.getRenderingMesh();
  86105. var scene = this._scene;
  86106. var engine = scene.getEngine();
  86107. if (!material) {
  86108. return;
  86109. }
  86110. // Do not block in blend mode.
  86111. if (material.needAlphaBlendingForMesh(mesh)) {
  86112. return;
  86113. }
  86114. // Culling
  86115. engine.setState(material.backFaceCulling);
  86116. // Managing instances
  86117. var batch = mesh._getInstancesRenderList(subMesh._id);
  86118. if (batch.mustReturn) {
  86119. return;
  86120. }
  86121. // Early Exit per mesh
  86122. if (!this._shouldRenderMesh(mesh)) {
  86123. return;
  86124. }
  86125. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  86126. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  86127. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  86128. engine.enableEffect(this._effectLayerMapGenerationEffect);
  86129. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  86130. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  86131. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  86132. // Alpha test
  86133. if (material && material.needAlphaTesting()) {
  86134. var alphaTexture = material.getAlphaTestTexture();
  86135. if (alphaTexture) {
  86136. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  86137. var textureMatrix = alphaTexture.getTextureMatrix();
  86138. if (textureMatrix) {
  86139. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  86140. }
  86141. }
  86142. }
  86143. // Glow emissive only
  86144. if (this._emissiveTextureAndColor.texture) {
  86145. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  86146. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  86147. }
  86148. // Bones
  86149. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  86150. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  86151. }
  86152. // Draw
  86153. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  86154. }
  86155. else {
  86156. // Need to reset refresh rate of the shadowMap
  86157. this._mainTexture.resetRefreshCounter();
  86158. }
  86159. };
  86160. /**
  86161. * Rebuild the required buffers.
  86162. * @ignore Internal use only.
  86163. */
  86164. EffectLayer.prototype._rebuild = function () {
  86165. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86166. if (vb) {
  86167. vb._rebuild();
  86168. }
  86169. this._generateIndexBuffer();
  86170. };
  86171. /**
  86172. * Dispose only the render target textures and post process.
  86173. */
  86174. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  86175. this._mainTexture.dispose();
  86176. for (var i = 0; i < this._postProcesses.length; i++) {
  86177. if (this._postProcesses[i]) {
  86178. this._postProcesses[i].dispose();
  86179. }
  86180. }
  86181. this._postProcesses = [];
  86182. for (var i = 0; i < this._textures.length; i++) {
  86183. if (this._textures[i]) {
  86184. this._textures[i].dispose();
  86185. }
  86186. }
  86187. this._textures = [];
  86188. };
  86189. /**
  86190. * Dispose the highlight layer and free resources.
  86191. */
  86192. EffectLayer.prototype.dispose = function () {
  86193. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86194. if (vertexBuffer) {
  86195. vertexBuffer.dispose();
  86196. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86197. }
  86198. if (this._indexBuffer) {
  86199. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86200. this._indexBuffer = null;
  86201. }
  86202. // Clean textures and post processes
  86203. this._disposeTextureAndPostProcesses();
  86204. // Remove from scene
  86205. var index = this._scene.effectLayers.indexOf(this, 0);
  86206. if (index > -1) {
  86207. this._scene.effectLayers.splice(index, 1);
  86208. }
  86209. // Callback
  86210. this.onDisposeObservable.notifyObservers(this);
  86211. this.onDisposeObservable.clear();
  86212. this.onBeforeRenderMainTextureObservable.clear();
  86213. this.onBeforeComposeObservable.clear();
  86214. this.onAfterComposeObservable.clear();
  86215. this.onSizeChangedObservable.clear();
  86216. };
  86217. return EffectLayer;
  86218. }());
  86219. BABYLON.EffectLayer = EffectLayer;
  86220. })(BABYLON || (BABYLON = {}));
  86221. //# sourceMappingURL=babylon.effectLayer.js.map
  86222. var BABYLON;
  86223. (function (BABYLON) {
  86224. /**
  86225. * Special Glow Blur post process only blurring the alpha channel
  86226. * It enforces keeping the most luminous color in the color channel.
  86227. */
  86228. var GlowBlurPostProcess = /** @class */ (function (_super) {
  86229. __extends(GlowBlurPostProcess, _super);
  86230. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  86231. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  86232. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  86233. _this.direction = direction;
  86234. _this.kernel = kernel;
  86235. _this.onApplyObservable.add(function (effect) {
  86236. effect.setFloat2("screenSize", _this.width, _this.height);
  86237. effect.setVector2("direction", _this.direction);
  86238. effect.setFloat("blurWidth", _this.kernel);
  86239. });
  86240. return _this;
  86241. }
  86242. return GlowBlurPostProcess;
  86243. }(BABYLON.PostProcess));
  86244. /**
  86245. * The highlight layer Helps adding a glow effect around a mesh.
  86246. *
  86247. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  86248. * glowy meshes to your scene.
  86249. *
  86250. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  86251. */
  86252. var HighlightLayer = /** @class */ (function (_super) {
  86253. __extends(HighlightLayer, _super);
  86254. /**
  86255. * Instantiates a new highlight Layer and references it to the scene..
  86256. * @param name The name of the layer
  86257. * @param scene The scene to use the layer in
  86258. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  86259. */
  86260. function HighlightLayer(name, scene, options) {
  86261. var _this = _super.call(this, name, scene) || this;
  86262. _this.name = name;
  86263. /**
  86264. * Specifies whether or not the inner glow is ACTIVE in the layer.
  86265. */
  86266. _this.innerGlow = true;
  86267. /**
  86268. * Specifies whether or not the outer glow is ACTIVE in the layer.
  86269. */
  86270. _this.outerGlow = true;
  86271. /**
  86272. * An event triggered when the highlight layer is being blurred.
  86273. */
  86274. _this.onBeforeBlurObservable = new BABYLON.Observable();
  86275. /**
  86276. * An event triggered when the highlight layer has been blurred.
  86277. */
  86278. _this.onAfterBlurObservable = new BABYLON.Observable();
  86279. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  86280. _this._meshes = {};
  86281. _this._excludedMeshes = {};
  86282. _this.neutralColor = HighlightLayer.NeutralColor;
  86283. // Warn on stencil
  86284. if (!_this._engine.isStencilEnable) {
  86285. 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 }");
  86286. }
  86287. // Adapt options
  86288. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  86289. // Initialize the layer
  86290. _this._init({
  86291. alphaBlendingMode: _this._options.alphaBlendingMode,
  86292. camera: _this._options.camera,
  86293. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  86294. mainTextureRatio: _this._options.mainTextureRatio
  86295. });
  86296. // Do not render as long as no meshes have been added
  86297. _this._shouldRender = false;
  86298. return _this;
  86299. }
  86300. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  86301. /**
  86302. * Gets the horizontal size of the blur.
  86303. */
  86304. get: function () {
  86305. return this._horizontalBlurPostprocess.kernel;
  86306. },
  86307. /**
  86308. * Specifies the horizontal size of the blur.
  86309. */
  86310. set: function (value) {
  86311. this._horizontalBlurPostprocess.kernel = value;
  86312. },
  86313. enumerable: true,
  86314. configurable: true
  86315. });
  86316. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  86317. /**
  86318. * Gets the vertical size of the blur.
  86319. */
  86320. get: function () {
  86321. return this._verticalBlurPostprocess.kernel;
  86322. },
  86323. /**
  86324. * Specifies the vertical size of the blur.
  86325. */
  86326. set: function (value) {
  86327. this._verticalBlurPostprocess.kernel = value;
  86328. },
  86329. enumerable: true,
  86330. configurable: true
  86331. });
  86332. /**
  86333. * Get the effect name of the layer.
  86334. * @return The effect name
  86335. */
  86336. HighlightLayer.prototype.getEffectName = function () {
  86337. return HighlightLayer.EffectName;
  86338. };
  86339. /**
  86340. * Create the merge effect. This is the shader use to blit the information back
  86341. * to the main canvas at the end of the scene rendering.
  86342. */
  86343. HighlightLayer.prototype._createMergeEffect = function () {
  86344. // Effect
  86345. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  86346. };
  86347. /**
  86348. * Creates the render target textures and post processes used in the highlight layer.
  86349. */
  86350. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  86351. var _this = this;
  86352. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  86353. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  86354. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  86355. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  86356. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  86357. width: blurTextureWidth,
  86358. height: blurTextureHeight
  86359. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86360. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86361. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86362. this._blurTexture.anisotropicFilteringLevel = 16;
  86363. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  86364. this._blurTexture.renderParticles = false;
  86365. this._blurTexture.ignoreCameraViewport = true;
  86366. this._textures = [this._blurTexture];
  86367. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  86368. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86369. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  86370. effect.setTexture("textureSampler", _this._mainTexture);
  86371. });
  86372. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86373. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  86374. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  86375. });
  86376. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86377. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  86378. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  86379. });
  86380. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  86381. }
  86382. else {
  86383. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  86384. width: blurTextureWidth,
  86385. height: blurTextureHeight
  86386. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86387. this._horizontalBlurPostprocess.width = blurTextureWidth;
  86388. this._horizontalBlurPostprocess.height = blurTextureHeight;
  86389. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  86390. effect.setTexture("textureSampler", _this._mainTexture);
  86391. });
  86392. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  86393. width: blurTextureWidth,
  86394. height: blurTextureHeight
  86395. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86396. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  86397. }
  86398. this._mainTexture.onAfterUnbindObservable.add(function () {
  86399. _this.onBeforeBlurObservable.notifyObservers(_this);
  86400. var internalTexture = _this._blurTexture.getInternalTexture();
  86401. if (internalTexture) {
  86402. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  86403. }
  86404. _this.onAfterBlurObservable.notifyObservers(_this);
  86405. });
  86406. // Prevent autoClear.
  86407. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  86408. };
  86409. /**
  86410. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  86411. */
  86412. HighlightLayer.prototype.needStencil = function () {
  86413. return true;
  86414. };
  86415. /**
  86416. * Checks for the readiness of the element composing the layer.
  86417. * @param subMesh the mesh to check for
  86418. * @param useInstances specify wether or not to use instances to render the mesh
  86419. * @param emissiveTexture the associated emissive texture used to generate the glow
  86420. * @return true if ready otherwise, false
  86421. */
  86422. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  86423. var material = subMesh.getMaterial();
  86424. var mesh = subMesh.getRenderingMesh();
  86425. if (!material || !mesh || !this._meshes) {
  86426. return false;
  86427. }
  86428. var emissiveTexture = null;
  86429. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  86430. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  86431. emissiveTexture = material.emissiveTexture;
  86432. }
  86433. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  86434. };
  86435. /**
  86436. * Implementation specific of rendering the generating effect on the main canvas.
  86437. * @param effect The effect used to render through
  86438. */
  86439. HighlightLayer.prototype._internalRender = function (effect) {
  86440. // Texture
  86441. effect.setTexture("textureSampler", this._blurTexture);
  86442. // Cache
  86443. var engine = this._engine;
  86444. var previousStencilBuffer = engine.getStencilBuffer();
  86445. var previousStencilFunction = engine.getStencilFunction();
  86446. var previousStencilMask = engine.getStencilMask();
  86447. var previousStencilOperationPass = engine.getStencilOperationPass();
  86448. var previousStencilOperationFail = engine.getStencilOperationFail();
  86449. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  86450. var previousStencilReference = engine.getStencilFunctionReference();
  86451. // Stencil operations
  86452. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  86453. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  86454. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  86455. // Draw order
  86456. engine.setStencilMask(0x00);
  86457. engine.setStencilBuffer(true);
  86458. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  86459. // 2 passes inner outer
  86460. if (this.outerGlow) {
  86461. effect.setFloat("offset", 0);
  86462. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  86463. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86464. }
  86465. if (this.innerGlow) {
  86466. effect.setFloat("offset", 1);
  86467. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  86468. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86469. }
  86470. // Restore Cache
  86471. engine.setStencilFunction(previousStencilFunction);
  86472. engine.setStencilMask(previousStencilMask);
  86473. engine.setStencilBuffer(previousStencilBuffer);
  86474. engine.setStencilOperationPass(previousStencilOperationPass);
  86475. engine.setStencilOperationFail(previousStencilOperationFail);
  86476. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  86477. engine.setStencilFunctionReference(previousStencilReference);
  86478. };
  86479. /**
  86480. * Returns true if the layer contains information to display, otherwise false.
  86481. */
  86482. HighlightLayer.prototype.shouldRender = function () {
  86483. if (_super.prototype.shouldRender.call(this)) {
  86484. return this._meshes ? true : false;
  86485. }
  86486. return false;
  86487. };
  86488. /**
  86489. * Returns true if the mesh should render, otherwise false.
  86490. * @param mesh The mesh to render
  86491. * @returns true if it should render otherwise false
  86492. */
  86493. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  86494. // Excluded Mesh
  86495. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  86496. return false;
  86497. }
  86498. ;
  86499. return true;
  86500. };
  86501. /**
  86502. * Sets the required values for both the emissive texture and and the main color.
  86503. */
  86504. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  86505. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  86506. if (highlightLayerMesh) {
  86507. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  86508. }
  86509. else {
  86510. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  86511. }
  86512. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  86513. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  86514. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  86515. }
  86516. else {
  86517. this._emissiveTextureAndColor.texture = null;
  86518. }
  86519. };
  86520. /**
  86521. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  86522. * @param mesh The mesh to exclude from the highlight layer
  86523. */
  86524. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  86525. if (!this._excludedMeshes) {
  86526. return;
  86527. }
  86528. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  86529. if (!meshExcluded) {
  86530. this._excludedMeshes[mesh.uniqueId] = {
  86531. mesh: mesh,
  86532. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  86533. mesh.getEngine().setStencilBuffer(false);
  86534. }),
  86535. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  86536. mesh.getEngine().setStencilBuffer(true);
  86537. }),
  86538. };
  86539. }
  86540. };
  86541. /**
  86542. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  86543. * @param mesh The mesh to highlight
  86544. */
  86545. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  86546. if (!this._excludedMeshes) {
  86547. return;
  86548. }
  86549. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  86550. if (meshExcluded) {
  86551. if (meshExcluded.beforeRender) {
  86552. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  86553. }
  86554. if (meshExcluded.afterRender) {
  86555. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  86556. }
  86557. }
  86558. this._excludedMeshes[mesh.uniqueId] = null;
  86559. };
  86560. /**
  86561. * Determine if a given mesh will be highlighted by the current HighlightLayer
  86562. * @param mesh mesh to test
  86563. * @returns true if the mesh will be highlighted by the current HighlightLayer
  86564. */
  86565. HighlightLayer.prototype.hasMesh = function (mesh) {
  86566. if (!this._meshes) {
  86567. return false;
  86568. }
  86569. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  86570. };
  86571. /**
  86572. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  86573. * @param mesh The mesh to highlight
  86574. * @param color The color of the highlight
  86575. * @param glowEmissiveOnly Extract the glow from the emissive texture
  86576. */
  86577. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  86578. var _this = this;
  86579. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  86580. if (!this._meshes) {
  86581. return;
  86582. }
  86583. var meshHighlight = this._meshes[mesh.uniqueId];
  86584. if (meshHighlight) {
  86585. meshHighlight.color = color;
  86586. }
  86587. else {
  86588. this._meshes[mesh.uniqueId] = {
  86589. mesh: mesh,
  86590. color: color,
  86591. // Lambda required for capture due to Observable this context
  86592. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  86593. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  86594. _this._defaultStencilReference(mesh);
  86595. }
  86596. else {
  86597. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  86598. }
  86599. }),
  86600. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  86601. glowEmissiveOnly: glowEmissiveOnly
  86602. };
  86603. }
  86604. this._shouldRender = true;
  86605. };
  86606. /**
  86607. * Remove a mesh from the highlight layer in order to make it stop glowing.
  86608. * @param mesh The mesh to highlight
  86609. */
  86610. HighlightLayer.prototype.removeMesh = function (mesh) {
  86611. if (!this._meshes) {
  86612. return;
  86613. }
  86614. var meshHighlight = this._meshes[mesh.uniqueId];
  86615. if (meshHighlight) {
  86616. if (meshHighlight.observerHighlight) {
  86617. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  86618. }
  86619. if (meshHighlight.observerDefault) {
  86620. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  86621. }
  86622. delete this._meshes[mesh.uniqueId];
  86623. }
  86624. this._shouldRender = false;
  86625. for (var meshHighlightToCheck in this._meshes) {
  86626. if (this._meshes[meshHighlightToCheck]) {
  86627. this._shouldRender = true;
  86628. break;
  86629. }
  86630. }
  86631. };
  86632. /**
  86633. * Force the stencil to the normal expected value for none glowing parts
  86634. */
  86635. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  86636. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  86637. };
  86638. /**
  86639. * Free any resources and references associated to a mesh.
  86640. * Internal use
  86641. * @param mesh The mesh to free.
  86642. */
  86643. HighlightLayer.prototype._disposeMesh = function (mesh) {
  86644. this.removeMesh(mesh);
  86645. this.removeExcludedMesh(mesh);
  86646. };
  86647. /**
  86648. * Dispose the highlight layer and free resources.
  86649. */
  86650. HighlightLayer.prototype.dispose = function () {
  86651. if (this._meshes) {
  86652. // Clean mesh references
  86653. for (var id in this._meshes) {
  86654. var meshHighlight = this._meshes[id];
  86655. if (meshHighlight && meshHighlight.mesh) {
  86656. if (meshHighlight.observerHighlight) {
  86657. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  86658. }
  86659. if (meshHighlight.observerDefault) {
  86660. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  86661. }
  86662. }
  86663. }
  86664. this._meshes = null;
  86665. }
  86666. if (this._excludedMeshes) {
  86667. for (var id in this._excludedMeshes) {
  86668. var meshHighlight = this._excludedMeshes[id];
  86669. if (meshHighlight) {
  86670. if (meshHighlight.beforeRender) {
  86671. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  86672. }
  86673. if (meshHighlight.afterRender) {
  86674. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  86675. }
  86676. }
  86677. }
  86678. this._excludedMeshes = null;
  86679. }
  86680. _super.prototype.dispose.call(this);
  86681. };
  86682. /**
  86683. * Effect Name of the highlight layer.
  86684. */
  86685. HighlightLayer.EffectName = "HighlightLayer";
  86686. /**
  86687. * The neutral color used during the preparation of the glow effect.
  86688. * This is black by default as the blend operation is a blend operation.
  86689. */
  86690. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  86691. /**
  86692. * Stencil value used for glowing meshes.
  86693. */
  86694. HighlightLayer.GlowingMeshStencilReference = 0x02;
  86695. /**
  86696. * Stencil value used for the other meshes in the scene.
  86697. */
  86698. HighlightLayer.NormalMeshStencilReference = 0x01;
  86699. return HighlightLayer;
  86700. }(BABYLON.EffectLayer));
  86701. BABYLON.HighlightLayer = HighlightLayer;
  86702. })(BABYLON || (BABYLON = {}));
  86703. //# sourceMappingURL=babylon.highlightLayer.js.map
  86704. var BABYLON;
  86705. (function (BABYLON) {
  86706. /**
  86707. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  86708. *
  86709. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  86710. * glowy meshes to your scene.
  86711. *
  86712. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  86713. */
  86714. var GlowLayer = /** @class */ (function (_super) {
  86715. __extends(GlowLayer, _super);
  86716. /**
  86717. * Instantiates a new glow Layer and references it to the scene.
  86718. * @param name The name of the layer
  86719. * @param scene The scene to use the layer in
  86720. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  86721. */
  86722. function GlowLayer(name, scene, options) {
  86723. var _this = _super.call(this, name, scene) || this;
  86724. _this.name = name;
  86725. _this._intensity = 1.0;
  86726. _this._includedOnlyMeshes = [];
  86727. _this._excludedMeshes = [];
  86728. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  86729. // Adapt options
  86730. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  86731. // Initialize the layer
  86732. _this._init({
  86733. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  86734. camera: _this._options.camera,
  86735. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  86736. mainTextureRatio: _this._options.mainTextureRatio
  86737. });
  86738. return _this;
  86739. }
  86740. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  86741. /**
  86742. * Gets the kernel size of the blur.
  86743. */
  86744. get: function () {
  86745. return this._horizontalBlurPostprocess1.kernel;
  86746. },
  86747. /**
  86748. * Sets the kernel size of the blur.
  86749. */
  86750. set: function (value) {
  86751. this._horizontalBlurPostprocess1.kernel = value;
  86752. this._verticalBlurPostprocess1.kernel = value;
  86753. this._horizontalBlurPostprocess2.kernel = value;
  86754. this._verticalBlurPostprocess2.kernel = value;
  86755. },
  86756. enumerable: true,
  86757. configurable: true
  86758. });
  86759. Object.defineProperty(GlowLayer.prototype, "intensity", {
  86760. /**
  86761. * Gets the glow intensity.
  86762. */
  86763. get: function () {
  86764. return this._intensity;
  86765. },
  86766. /**
  86767. * Sets the glow intensity.
  86768. */
  86769. set: function (value) {
  86770. this._intensity = value;
  86771. },
  86772. enumerable: true,
  86773. configurable: true
  86774. });
  86775. /**
  86776. * Get the effect name of the layer.
  86777. * @return The effect name
  86778. */
  86779. GlowLayer.prototype.getEffectName = function () {
  86780. return GlowLayer.EffectName;
  86781. };
  86782. /**
  86783. * Create the merge effect. This is the shader use to blit the information back
  86784. * to the main canvas at the end of the scene rendering.
  86785. */
  86786. GlowLayer.prototype._createMergeEffect = function () {
  86787. // Effect
  86788. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  86789. };
  86790. /**
  86791. * Creates the render target textures and post processes used in the glow layer.
  86792. */
  86793. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  86794. var _this = this;
  86795. var blurTextureWidth = this._mainTextureDesiredSize.width;
  86796. var blurTextureHeight = this._mainTextureDesiredSize.height;
  86797. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  86798. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  86799. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  86800. width: blurTextureWidth,
  86801. height: blurTextureHeight
  86802. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86803. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86804. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86805. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86806. this._blurTexture1.renderParticles = false;
  86807. this._blurTexture1.ignoreCameraViewport = true;
  86808. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  86809. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  86810. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  86811. width: blurTextureWidth2,
  86812. height: blurTextureHeight2
  86813. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86814. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86815. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86816. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86817. this._blurTexture2.renderParticles = false;
  86818. this._blurTexture2.ignoreCameraViewport = true;
  86819. this._textures = [this._blurTexture1, this._blurTexture2];
  86820. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  86821. width: blurTextureWidth,
  86822. height: blurTextureHeight
  86823. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86824. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  86825. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  86826. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  86827. effect.setTexture("textureSampler", _this._mainTexture);
  86828. });
  86829. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  86830. width: blurTextureWidth,
  86831. height: blurTextureHeight
  86832. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86833. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  86834. width: blurTextureWidth2,
  86835. height: blurTextureHeight2
  86836. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86837. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  86838. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  86839. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  86840. effect.setTexture("textureSampler", _this._blurTexture1);
  86841. });
  86842. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  86843. width: blurTextureWidth2,
  86844. height: blurTextureHeight2
  86845. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86846. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  86847. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  86848. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  86849. this._mainTexture.samples = this._options.mainTextureSamples;
  86850. this._mainTexture.onAfterUnbindObservable.add(function () {
  86851. var internalTexture = _this._blurTexture1.getInternalTexture();
  86852. if (internalTexture) {
  86853. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  86854. internalTexture = _this._blurTexture2.getInternalTexture();
  86855. if (internalTexture) {
  86856. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  86857. }
  86858. }
  86859. });
  86860. // Prevent autoClear.
  86861. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  86862. };
  86863. /**
  86864. * Checks for the readiness of the element composing the layer.
  86865. * @param subMesh the mesh to check for
  86866. * @param useInstances specify wether or not to use instances to render the mesh
  86867. * @param emissiveTexture the associated emissive texture used to generate the glow
  86868. * @return true if ready otherwise, false
  86869. */
  86870. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  86871. var material = subMesh.getMaterial();
  86872. var mesh = subMesh.getRenderingMesh();
  86873. if (!material || !mesh) {
  86874. return false;
  86875. }
  86876. var emissiveTexture = material.emissiveTexture;
  86877. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  86878. };
  86879. /**
  86880. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  86881. */
  86882. GlowLayer.prototype.needStencil = function () {
  86883. return false;
  86884. };
  86885. /**
  86886. * Implementation specific of rendering the generating effect on the main canvas.
  86887. * @param effect The effect used to render through
  86888. */
  86889. GlowLayer.prototype._internalRender = function (effect) {
  86890. // Texture
  86891. effect.setTexture("textureSampler", this._blurTexture1);
  86892. effect.setTexture("textureSampler2", this._blurTexture2);
  86893. effect.setFloat("offset", this._intensity);
  86894. // Cache
  86895. var engine = this._engine;
  86896. var previousStencilBuffer = engine.getStencilBuffer();
  86897. // Draw order
  86898. engine.setStencilBuffer(false);
  86899. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86900. // Draw order
  86901. engine.setStencilBuffer(previousStencilBuffer);
  86902. };
  86903. /**
  86904. * Sets the required values for both the emissive texture and and the main color.
  86905. */
  86906. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  86907. var textureLevel = 1.0;
  86908. if (this.customEmissiveTextureSelector) {
  86909. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  86910. }
  86911. else {
  86912. if (material) {
  86913. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  86914. if (this._emissiveTextureAndColor.texture) {
  86915. textureLevel = this._emissiveTextureAndColor.texture.level;
  86916. }
  86917. }
  86918. else {
  86919. this._emissiveTextureAndColor.texture = null;
  86920. }
  86921. }
  86922. if (this.customEmissiveColorSelector) {
  86923. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  86924. }
  86925. else {
  86926. if (material.emissiveColor) {
  86927. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  86928. }
  86929. else {
  86930. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  86931. }
  86932. }
  86933. };
  86934. /**
  86935. * Returns true if the mesh should render, otherwise false.
  86936. * @param mesh The mesh to render
  86937. * @returns true if it should render otherwise false
  86938. */
  86939. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  86940. return this.hasMesh(mesh);
  86941. };
  86942. /**
  86943. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  86944. * @param mesh The mesh to exclude from the glow layer
  86945. */
  86946. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  86947. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  86948. this._excludedMeshes.push(mesh.uniqueId);
  86949. }
  86950. };
  86951. /**
  86952. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  86953. * @param mesh The mesh to remove
  86954. */
  86955. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  86956. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  86957. if (index !== -1) {
  86958. this._excludedMeshes.splice(index, 1);
  86959. }
  86960. };
  86961. /**
  86962. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  86963. * @param mesh The mesh to include in the glow layer
  86964. */
  86965. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  86966. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  86967. this._includedOnlyMeshes.push(mesh.uniqueId);
  86968. }
  86969. };
  86970. /**
  86971. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  86972. * @param mesh The mesh to remove
  86973. */
  86974. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  86975. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  86976. if (index !== -1) {
  86977. this._includedOnlyMeshes.splice(index, 1);
  86978. }
  86979. };
  86980. /**
  86981. * Determine if a given mesh will be used in the glow layer
  86982. * @param mesh The mesh to test
  86983. * @returns true if the mesh will be highlighted by the current glow layer
  86984. */
  86985. GlowLayer.prototype.hasMesh = function (mesh) {
  86986. // Included Mesh
  86987. if (this._includedOnlyMeshes.length) {
  86988. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  86989. }
  86990. ;
  86991. // Excluded Mesh
  86992. if (this._excludedMeshes.length) {
  86993. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  86994. }
  86995. ;
  86996. return true;
  86997. };
  86998. /**
  86999. * Free any resources and references associated to a mesh.
  87000. * Internal use
  87001. * @param mesh The mesh to free.
  87002. */
  87003. GlowLayer.prototype._disposeMesh = function (mesh) {
  87004. this.removeIncludedOnlyMesh(mesh);
  87005. this.removeExcludedMesh(mesh);
  87006. };
  87007. /**
  87008. * Effect Name of the layer.
  87009. */
  87010. GlowLayer.EffectName = "GlowLayer";
  87011. /**
  87012. * The default blur kernel size used for the glow.
  87013. */
  87014. GlowLayer.DefaultBlurKernelSize = 32;
  87015. /**
  87016. * The default texture size ratio used for the glow.
  87017. */
  87018. GlowLayer.DefaultTextureRatio = 0.5;
  87019. return GlowLayer;
  87020. }(BABYLON.EffectLayer));
  87021. BABYLON.GlowLayer = GlowLayer;
  87022. })(BABYLON || (BABYLON = {}));
  87023. //# sourceMappingURL=babylon.glowLayer.js.map
  87024. var BABYLON;
  87025. (function (BABYLON) {
  87026. /**
  87027. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  87028. */
  87029. var AssetTaskState;
  87030. (function (AssetTaskState) {
  87031. /**
  87032. * Initialization
  87033. */
  87034. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  87035. /**
  87036. * Running
  87037. */
  87038. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  87039. /**
  87040. * Done
  87041. */
  87042. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  87043. /**
  87044. * Error
  87045. */
  87046. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  87047. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  87048. /**
  87049. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  87050. */
  87051. var AbstractAssetTask = /** @class */ (function () {
  87052. /**
  87053. * Creates a new {BABYLON.AssetsManager}
  87054. * @param name defines the name of the task
  87055. */
  87056. function AbstractAssetTask(
  87057. /**
  87058. * Task name
  87059. */ name) {
  87060. this.name = name;
  87061. this._isCompleted = false;
  87062. this._taskState = AssetTaskState.INIT;
  87063. }
  87064. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  87065. /**
  87066. * Get if the task is completed
  87067. */
  87068. get: function () {
  87069. return this._isCompleted;
  87070. },
  87071. enumerable: true,
  87072. configurable: true
  87073. });
  87074. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  87075. /**
  87076. * Gets the current state of the task
  87077. */
  87078. get: function () {
  87079. return this._taskState;
  87080. },
  87081. enumerable: true,
  87082. configurable: true
  87083. });
  87084. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  87085. /**
  87086. * Gets the current error object (if task is in error)
  87087. */
  87088. get: function () {
  87089. return this._errorObject;
  87090. },
  87091. enumerable: true,
  87092. configurable: true
  87093. });
  87094. /**
  87095. * Internal only
  87096. * @ignore
  87097. */
  87098. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  87099. if (this._errorObject) {
  87100. return;
  87101. }
  87102. this._errorObject = {
  87103. message: message,
  87104. exception: exception
  87105. };
  87106. };
  87107. /**
  87108. * Execute the current task
  87109. * @param scene defines the scene where you want your assets to be loaded
  87110. * @param onSuccess is a callback called when the task is successfully executed
  87111. * @param onError is a callback called if an error occurs
  87112. */
  87113. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  87114. var _this = this;
  87115. this._taskState = AssetTaskState.RUNNING;
  87116. this.runTask(scene, function () {
  87117. _this.onDoneCallback(onSuccess, onError);
  87118. }, function (msg, exception) {
  87119. _this.onErrorCallback(onError, msg, exception);
  87120. });
  87121. };
  87122. /**
  87123. * Execute the current task
  87124. * @param scene defines the scene where you want your assets to be loaded
  87125. * @param onSuccess is a callback called when the task is successfully executed
  87126. * @param onError is a callback called if an error occurs
  87127. */
  87128. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87129. throw new Error("runTask is not implemented");
  87130. };
  87131. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  87132. this._taskState = AssetTaskState.ERROR;
  87133. this._errorObject = {
  87134. message: message,
  87135. exception: exception
  87136. };
  87137. if (this.onError) {
  87138. this.onError(this, message, exception);
  87139. }
  87140. onError();
  87141. };
  87142. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  87143. try {
  87144. this._taskState = AssetTaskState.DONE;
  87145. this._isCompleted = true;
  87146. if (this.onSuccess) {
  87147. this.onSuccess(this);
  87148. }
  87149. onSuccess();
  87150. }
  87151. catch (e) {
  87152. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  87153. }
  87154. };
  87155. return AbstractAssetTask;
  87156. }());
  87157. BABYLON.AbstractAssetTask = AbstractAssetTask;
  87158. /**
  87159. * Class used to share progress information about assets loading
  87160. */
  87161. var AssetsProgressEvent = /** @class */ (function () {
  87162. /**
  87163. * Creates a {BABYLON.AssetsProgressEvent}
  87164. * @param remainingCount defines the number of remaining tasks to process
  87165. * @param totalCount defines the total number of tasks
  87166. * @param task defines the task that was just processed
  87167. */
  87168. function AssetsProgressEvent(remainingCount, totalCount, task) {
  87169. this.remainingCount = remainingCount;
  87170. this.totalCount = totalCount;
  87171. this.task = task;
  87172. }
  87173. return AssetsProgressEvent;
  87174. }());
  87175. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  87176. /**
  87177. * Define a task used by {BABYLON.AssetsManager} to load meshes
  87178. */
  87179. var MeshAssetTask = /** @class */ (function (_super) {
  87180. __extends(MeshAssetTask, _super);
  87181. /**
  87182. * Creates a new {BABYLON.MeshAssetTask}
  87183. * @param name defines the name of the task
  87184. * @param meshesNames defines the list of mesh's names you want to load
  87185. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  87186. * @param sceneFilename defines the filename of the scene to load from
  87187. */
  87188. function MeshAssetTask(
  87189. /**
  87190. * Defines the name of the task
  87191. */
  87192. name,
  87193. /**
  87194. * Defines the list of mesh's names you want to load
  87195. */
  87196. meshesNames,
  87197. /**
  87198. * Defines the root url to use as a base to load your meshes and associated resources
  87199. */
  87200. rootUrl,
  87201. /**
  87202. * Defines the filename of the scene to load from
  87203. */
  87204. sceneFilename) {
  87205. var _this = _super.call(this, name) || this;
  87206. _this.name = name;
  87207. _this.meshesNames = meshesNames;
  87208. _this.rootUrl = rootUrl;
  87209. _this.sceneFilename = sceneFilename;
  87210. return _this;
  87211. }
  87212. /**
  87213. * Execute the current task
  87214. * @param scene defines the scene where you want your assets to be loaded
  87215. * @param onSuccess is a callback called when the task is successfully executed
  87216. * @param onError is a callback called if an error occurs
  87217. */
  87218. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87219. var _this = this;
  87220. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  87221. _this.loadedMeshes = meshes;
  87222. _this.loadedParticleSystems = particleSystems;
  87223. _this.loadedSkeletons = skeletons;
  87224. onSuccess();
  87225. }, null, function (scene, message, exception) {
  87226. onError(message, exception);
  87227. });
  87228. };
  87229. return MeshAssetTask;
  87230. }(AbstractAssetTask));
  87231. BABYLON.MeshAssetTask = MeshAssetTask;
  87232. /**
  87233. * Define a task used by {BABYLON.AssetsManager} to load text content
  87234. */
  87235. var TextFileAssetTask = /** @class */ (function (_super) {
  87236. __extends(TextFileAssetTask, _super);
  87237. /**
  87238. * Creates a new TextFileAssetTask object
  87239. * @param name defines the name of the task
  87240. * @param url defines the location of the file to load
  87241. */
  87242. function TextFileAssetTask(
  87243. /**
  87244. * Defines the name of the task
  87245. */
  87246. name,
  87247. /**
  87248. * Defines the location of the file to load
  87249. */
  87250. url) {
  87251. var _this = _super.call(this, name) || this;
  87252. _this.name = name;
  87253. _this.url = url;
  87254. return _this;
  87255. }
  87256. /**
  87257. * Execute the current task
  87258. * @param scene defines the scene where you want your assets to be loaded
  87259. * @param onSuccess is a callback called when the task is successfully executed
  87260. * @param onError is a callback called if an error occurs
  87261. */
  87262. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87263. var _this = this;
  87264. scene._loadFile(this.url, function (data) {
  87265. _this.text = data;
  87266. onSuccess();
  87267. }, undefined, false, false, function (request, exception) {
  87268. if (request) {
  87269. onError(request.status + " " + request.statusText, exception);
  87270. }
  87271. });
  87272. };
  87273. return TextFileAssetTask;
  87274. }(AbstractAssetTask));
  87275. BABYLON.TextFileAssetTask = TextFileAssetTask;
  87276. /**
  87277. * Define a task used by {BABYLON.AssetsManager} to load binary data
  87278. */
  87279. var BinaryFileAssetTask = /** @class */ (function (_super) {
  87280. __extends(BinaryFileAssetTask, _super);
  87281. /**
  87282. * Creates a new BinaryFileAssetTask object
  87283. * @param name defines the name of the new task
  87284. * @param url defines the location of the file to load
  87285. */
  87286. function BinaryFileAssetTask(
  87287. /**
  87288. * Defines the name of the task
  87289. */
  87290. name,
  87291. /**
  87292. * Defines the location of the file to load
  87293. */
  87294. url) {
  87295. var _this = _super.call(this, name) || this;
  87296. _this.name = name;
  87297. _this.url = url;
  87298. return _this;
  87299. }
  87300. /**
  87301. * Execute the current task
  87302. * @param scene defines the scene where you want your assets to be loaded
  87303. * @param onSuccess is a callback called when the task is successfully executed
  87304. * @param onError is a callback called if an error occurs
  87305. */
  87306. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87307. var _this = this;
  87308. scene._loadFile(this.url, function (data) {
  87309. _this.data = data;
  87310. onSuccess();
  87311. }, undefined, true, true, function (request, exception) {
  87312. if (request) {
  87313. onError(request.status + " " + request.statusText, exception);
  87314. }
  87315. });
  87316. };
  87317. return BinaryFileAssetTask;
  87318. }(AbstractAssetTask));
  87319. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  87320. /**
  87321. * Define a task used by {BABYLON.AssetsManager} to load images
  87322. */
  87323. var ImageAssetTask = /** @class */ (function (_super) {
  87324. __extends(ImageAssetTask, _super);
  87325. /**
  87326. * Creates a new ImageAssetTask
  87327. * @param name defines the name of the task
  87328. * @param url defines the location of the image to load
  87329. */
  87330. function ImageAssetTask(
  87331. /**
  87332. * Defines the name of the task
  87333. */
  87334. name,
  87335. /**
  87336. * Defines the location of the image to load
  87337. */
  87338. url) {
  87339. var _this = _super.call(this, name) || this;
  87340. _this.name = name;
  87341. _this.url = url;
  87342. return _this;
  87343. }
  87344. /**
  87345. * Execute the current task
  87346. * @param scene defines the scene where you want your assets to be loaded
  87347. * @param onSuccess is a callback called when the task is successfully executed
  87348. * @param onError is a callback called if an error occurs
  87349. */
  87350. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87351. var _this = this;
  87352. var img = new Image();
  87353. BABYLON.Tools.SetCorsBehavior(this.url, img);
  87354. img.onload = function () {
  87355. _this.image = img;
  87356. onSuccess();
  87357. };
  87358. img.onerror = function (err) {
  87359. onError("Error loading image", err);
  87360. };
  87361. img.src = this.url;
  87362. };
  87363. return ImageAssetTask;
  87364. }(AbstractAssetTask));
  87365. BABYLON.ImageAssetTask = ImageAssetTask;
  87366. /**
  87367. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  87368. */
  87369. var TextureAssetTask = /** @class */ (function (_super) {
  87370. __extends(TextureAssetTask, _super);
  87371. /**
  87372. * Creates a new TextureAssetTask object
  87373. * @param name defines the name of the task
  87374. * @param url defines the location of the file to load
  87375. * @param noMipmap defines if mipmap should not be generated (default is false)
  87376. * @param invertY defines if texture must be inverted on Y axis (default is false)
  87377. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  87378. */
  87379. function TextureAssetTask(
  87380. /**
  87381. * Defines the name of the task
  87382. */
  87383. name,
  87384. /**
  87385. * Defines the location of the file to load
  87386. */
  87387. url,
  87388. /**
  87389. * Defines if mipmap should not be generated (default is false)
  87390. */
  87391. noMipmap,
  87392. /**
  87393. * Defines if texture must be inverted on Y axis (default is false)
  87394. */
  87395. invertY,
  87396. /**
  87397. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  87398. */
  87399. samplingMode) {
  87400. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  87401. var _this = _super.call(this, name) || this;
  87402. _this.name = name;
  87403. _this.url = url;
  87404. _this.noMipmap = noMipmap;
  87405. _this.invertY = invertY;
  87406. _this.samplingMode = samplingMode;
  87407. return _this;
  87408. }
  87409. /**
  87410. * Execute the current task
  87411. * @param scene defines the scene where you want your assets to be loaded
  87412. * @param onSuccess is a callback called when the task is successfully executed
  87413. * @param onError is a callback called if an error occurs
  87414. */
  87415. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87416. var onload = function () {
  87417. onSuccess();
  87418. };
  87419. var onerror = function (message, exception) {
  87420. onError(message, exception);
  87421. };
  87422. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  87423. };
  87424. return TextureAssetTask;
  87425. }(AbstractAssetTask));
  87426. BABYLON.TextureAssetTask = TextureAssetTask;
  87427. /**
  87428. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  87429. */
  87430. var CubeTextureAssetTask = /** @class */ (function (_super) {
  87431. __extends(CubeTextureAssetTask, _super);
  87432. /**
  87433. * Creates a new CubeTextureAssetTask
  87434. * @param name defines the name of the task
  87435. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  87436. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  87437. * @param noMipmap defines if mipmaps should not be generated (default is false)
  87438. * @param files defines the explicit list of files (undefined by default)
  87439. */
  87440. function CubeTextureAssetTask(
  87441. /**
  87442. * Defines the name of the task
  87443. */
  87444. name,
  87445. /**
  87446. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  87447. */
  87448. url,
  87449. /**
  87450. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  87451. */
  87452. extensions,
  87453. /**
  87454. * Defines if mipmaps should not be generated (default is false)
  87455. */
  87456. noMipmap,
  87457. /**
  87458. * Defines the explicit list of files (undefined by default)
  87459. */
  87460. files) {
  87461. var _this = _super.call(this, name) || this;
  87462. _this.name = name;
  87463. _this.url = url;
  87464. _this.extensions = extensions;
  87465. _this.noMipmap = noMipmap;
  87466. _this.files = files;
  87467. return _this;
  87468. }
  87469. /**
  87470. * Execute the current task
  87471. * @param scene defines the scene where you want your assets to be loaded
  87472. * @param onSuccess is a callback called when the task is successfully executed
  87473. * @param onError is a callback called if an error occurs
  87474. */
  87475. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87476. var onload = function () {
  87477. onSuccess();
  87478. };
  87479. var onerror = function (message, exception) {
  87480. onError(message, exception);
  87481. };
  87482. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  87483. };
  87484. return CubeTextureAssetTask;
  87485. }(AbstractAssetTask));
  87486. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  87487. /**
  87488. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  87489. */
  87490. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  87491. __extends(HDRCubeTextureAssetTask, _super);
  87492. /**
  87493. * Creates a new HDRCubeTextureAssetTask object
  87494. * @param name defines the name of the task
  87495. * @param url defines the location of the file to load
  87496. * @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.
  87497. * @param noMipmap defines if mipmaps should not be generated (default is false)
  87498. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  87499. * @param useInGammaSpace 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)
  87500. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  87501. */
  87502. function HDRCubeTextureAssetTask(
  87503. /**
  87504. * Defines the name of the task
  87505. */
  87506. name,
  87507. /**
  87508. * Defines the location of the file to load
  87509. */
  87510. url,
  87511. /**
  87512. * 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.
  87513. */
  87514. size,
  87515. /**
  87516. * Defines if mipmaps should not be generated (default is false)
  87517. */
  87518. noMipmap,
  87519. /**
  87520. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  87521. */
  87522. generateHarmonics,
  87523. /**
  87524. * 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)
  87525. */
  87526. useInGammaSpace,
  87527. /**
  87528. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  87529. */
  87530. usePMREMGenerator) {
  87531. if (noMipmap === void 0) { noMipmap = false; }
  87532. if (generateHarmonics === void 0) { generateHarmonics = true; }
  87533. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  87534. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  87535. var _this = _super.call(this, name) || this;
  87536. _this.name = name;
  87537. _this.url = url;
  87538. _this.size = size;
  87539. _this.noMipmap = noMipmap;
  87540. _this.generateHarmonics = generateHarmonics;
  87541. _this.useInGammaSpace = useInGammaSpace;
  87542. _this.usePMREMGenerator = usePMREMGenerator;
  87543. return _this;
  87544. }
  87545. /**
  87546. * Execute the current task
  87547. * @param scene defines the scene where you want your assets to be loaded
  87548. * @param onSuccess is a callback called when the task is successfully executed
  87549. * @param onError is a callback called if an error occurs
  87550. */
  87551. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  87552. var onload = function () {
  87553. onSuccess();
  87554. };
  87555. var onerror = function (message, exception) {
  87556. onError(message, exception);
  87557. };
  87558. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  87559. };
  87560. return HDRCubeTextureAssetTask;
  87561. }(AbstractAssetTask));
  87562. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  87563. /**
  87564. * This class can be used to easily import assets into a scene
  87565. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  87566. */
  87567. var AssetsManager = /** @class */ (function () {
  87568. /**
  87569. * Creates a new AssetsManager
  87570. * @param scene defines the scene to work on
  87571. */
  87572. function AssetsManager(scene) {
  87573. this._isLoading = false;
  87574. this._tasks = new Array();
  87575. this._waitingTasksCount = 0;
  87576. this._totalTasksCount = 0;
  87577. /**
  87578. * Observable called when all tasks are processed
  87579. */
  87580. this.onTaskSuccessObservable = new BABYLON.Observable();
  87581. /**
  87582. * Observable called when a task had an error
  87583. */
  87584. this.onTaskErrorObservable = new BABYLON.Observable();
  87585. /**
  87586. * Observable called when a task is successful
  87587. */
  87588. this.onTasksDoneObservable = new BABYLON.Observable();
  87589. /**
  87590. * Observable called when a task is done (whatever the result is)
  87591. */
  87592. this.onProgressObservable = new BABYLON.Observable();
  87593. /**
  87594. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  87595. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  87596. */
  87597. this.useDefaultLoadingScreen = true;
  87598. this._scene = scene;
  87599. }
  87600. /**
  87601. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  87602. * @param taskName defines the name of the new task
  87603. * @param meshesNames defines the name of meshes to load
  87604. * @param rootUrl defines the root url to use to locate files
  87605. * @param sceneFilename defines the filename of the scene file
  87606. * @returns a new {BABYLON.MeshAssetTask} object
  87607. */
  87608. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  87609. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  87610. this._tasks.push(task);
  87611. return task;
  87612. };
  87613. /**
  87614. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  87615. * @param taskName defines the name of the new task
  87616. * @param url defines the url of the file to load
  87617. * @returns a new {BABYLON.TextFileAssetTask} object
  87618. */
  87619. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  87620. var task = new TextFileAssetTask(taskName, url);
  87621. this._tasks.push(task);
  87622. return task;
  87623. };
  87624. /**
  87625. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  87626. * @param taskName defines the name of the new task
  87627. * @param url defines the url of the file to load
  87628. * @returns a new {BABYLON.BinaryFileAssetTask} object
  87629. */
  87630. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  87631. var task = new BinaryFileAssetTask(taskName, url);
  87632. this._tasks.push(task);
  87633. return task;
  87634. };
  87635. /**
  87636. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  87637. * @param taskName defines the name of the new task
  87638. * @param url defines the url of the file to load
  87639. * @returns a new {BABYLON.ImageAssetTask} object
  87640. */
  87641. AssetsManager.prototype.addImageTask = function (taskName, url) {
  87642. var task = new ImageAssetTask(taskName, url);
  87643. this._tasks.push(task);
  87644. return task;
  87645. };
  87646. /**
  87647. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  87648. * @param taskName defines the name of the new task
  87649. * @param url defines the url of the file to load
  87650. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  87651. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  87652. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  87653. * @returns a new {BABYLON.TextureAssetTask} object
  87654. */
  87655. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  87656. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  87657. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  87658. this._tasks.push(task);
  87659. return task;
  87660. };
  87661. /**
  87662. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  87663. * @param taskName defines the name of the new task
  87664. * @param url defines the url of the file to load
  87665. * @param extensions defines the extension to use to load the cube map (can be null)
  87666. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  87667. * @param files defines the list of files to load (can be null)
  87668. * @returns a new {BABYLON.CubeTextureAssetTask} object
  87669. */
  87670. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  87671. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  87672. this._tasks.push(task);
  87673. return task;
  87674. };
  87675. /**
  87676. *
  87677. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  87678. * @param taskName defines the name of the new task
  87679. * @param url defines the url of the file to load
  87680. * @param size defines the size you want for the cubemap (can be null)
  87681. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  87682. * @param generateHarmonics defines if you want to automatically generate (true by default)
  87683. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  87684. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  87685. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  87686. */
  87687. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  87688. if (noMipmap === void 0) { noMipmap = false; }
  87689. if (generateHarmonics === void 0) { generateHarmonics = true; }
  87690. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  87691. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  87692. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  87693. this._tasks.push(task);
  87694. return task;
  87695. };
  87696. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  87697. var _this = this;
  87698. this._waitingTasksCount--;
  87699. try {
  87700. if (task.taskState === AssetTaskState.DONE) {
  87701. // Let's remove successfull tasks
  87702. BABYLON.Tools.SetImmediate(function () {
  87703. var index = _this._tasks.indexOf(task);
  87704. if (index > -1) {
  87705. _this._tasks.splice(index, 1);
  87706. }
  87707. });
  87708. }
  87709. if (this.onProgress) {
  87710. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  87711. }
  87712. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  87713. }
  87714. catch (e) {
  87715. BABYLON.Tools.Error("Error running progress callbacks.");
  87716. console.log(e);
  87717. }
  87718. if (this._waitingTasksCount === 0) {
  87719. try {
  87720. if (this.onFinish) {
  87721. this.onFinish(this._tasks);
  87722. }
  87723. this.onTasksDoneObservable.notifyObservers(this._tasks);
  87724. }
  87725. catch (e) {
  87726. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  87727. console.log(e);
  87728. }
  87729. this._isLoading = false;
  87730. this._scene.getEngine().hideLoadingUI();
  87731. }
  87732. };
  87733. AssetsManager.prototype._runTask = function (task) {
  87734. var _this = this;
  87735. var done = function () {
  87736. try {
  87737. if (_this.onTaskSuccess) {
  87738. _this.onTaskSuccess(task);
  87739. }
  87740. _this.onTaskSuccessObservable.notifyObservers(task);
  87741. _this._decreaseWaitingTasksCount(task);
  87742. }
  87743. catch (e) {
  87744. error("Error executing task success callbacks", e);
  87745. }
  87746. };
  87747. var error = function (message, exception) {
  87748. task._setErrorObject(message, exception);
  87749. if (_this.onTaskError) {
  87750. _this.onTaskError(task);
  87751. }
  87752. _this.onTaskErrorObservable.notifyObservers(task);
  87753. _this._decreaseWaitingTasksCount(task);
  87754. };
  87755. task.run(this._scene, done, error);
  87756. };
  87757. /**
  87758. * Reset the {BABYLON.AssetsManager} and remove all tasks
  87759. * @return the current instance of the {BABYLON.AssetsManager}
  87760. */
  87761. AssetsManager.prototype.reset = function () {
  87762. this._isLoading = false;
  87763. this._tasks = new Array();
  87764. return this;
  87765. };
  87766. /**
  87767. * Start the loading process
  87768. * @return the current instance of the {BABYLON.AssetsManager}
  87769. */
  87770. AssetsManager.prototype.load = function () {
  87771. if (this._isLoading) {
  87772. return this;
  87773. }
  87774. this._isLoading = true;
  87775. this._waitingTasksCount = this._tasks.length;
  87776. this._totalTasksCount = this._tasks.length;
  87777. if (this._waitingTasksCount === 0) {
  87778. this._isLoading = false;
  87779. if (this.onFinish) {
  87780. this.onFinish(this._tasks);
  87781. }
  87782. this.onTasksDoneObservable.notifyObservers(this._tasks);
  87783. return this;
  87784. }
  87785. if (this.useDefaultLoadingScreen) {
  87786. this._scene.getEngine().displayLoadingUI();
  87787. }
  87788. for (var index = 0; index < this._tasks.length; index++) {
  87789. var task = this._tasks[index];
  87790. this._runTask(task);
  87791. }
  87792. return this;
  87793. };
  87794. return AssetsManager;
  87795. }());
  87796. BABYLON.AssetsManager = AssetsManager;
  87797. })(BABYLON || (BABYLON = {}));
  87798. //# sourceMappingURL=babylon.assetsManager.js.map
  87799. var BABYLON;
  87800. (function (BABYLON) {
  87801. var serializedGeometries = [];
  87802. var serializeGeometry = function (geometry, serializationGeometries) {
  87803. if (serializedGeometries[geometry.id]) {
  87804. return;
  87805. }
  87806. if (geometry.doNotSerialize) {
  87807. return;
  87808. }
  87809. if (geometry instanceof BABYLON.BoxGeometry) {
  87810. serializationGeometries.boxes.push(geometry.serialize());
  87811. }
  87812. else if (geometry instanceof BABYLON.SphereGeometry) {
  87813. serializationGeometries.spheres.push(geometry.serialize());
  87814. }
  87815. else if (geometry instanceof BABYLON.CylinderGeometry) {
  87816. serializationGeometries.cylinders.push(geometry.serialize());
  87817. }
  87818. else if (geometry instanceof BABYLON.TorusGeometry) {
  87819. serializationGeometries.toruses.push(geometry.serialize());
  87820. }
  87821. else if (geometry instanceof BABYLON.GroundGeometry) {
  87822. serializationGeometries.grounds.push(geometry.serialize());
  87823. }
  87824. else if (geometry instanceof BABYLON.Plane) {
  87825. serializationGeometries.planes.push(geometry.serialize());
  87826. }
  87827. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  87828. serializationGeometries.torusKnots.push(geometry.serialize());
  87829. }
  87830. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  87831. throw new Error("Unknown primitive type");
  87832. }
  87833. else {
  87834. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  87835. }
  87836. serializedGeometries[geometry.id] = true;
  87837. };
  87838. var serializeMesh = function (mesh, serializationScene) {
  87839. var serializationObject = {};
  87840. // Geometry
  87841. var geometry = mesh._geometry;
  87842. if (geometry) {
  87843. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  87844. // 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
  87845. serializeGeometry(geometry, serializationScene.geometries);
  87846. }
  87847. }
  87848. // Custom
  87849. if (mesh.serialize) {
  87850. mesh.serialize(serializationObject);
  87851. }
  87852. return serializationObject;
  87853. };
  87854. var finalizeSingleMesh = function (mesh, serializationObject) {
  87855. //only works if the mesh is already loaded
  87856. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  87857. //serialize material
  87858. if (mesh.material) {
  87859. if (mesh.material instanceof BABYLON.StandardMaterial) {
  87860. serializationObject.materials = serializationObject.materials || [];
  87861. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  87862. serializationObject.materials.push(mesh.material.serialize());
  87863. }
  87864. }
  87865. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  87866. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  87867. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  87868. serializationObject.multiMaterials.push(mesh.material.serialize());
  87869. }
  87870. }
  87871. }
  87872. //serialize geometry
  87873. var geometry = mesh._geometry;
  87874. if (geometry) {
  87875. if (!serializationObject.geometries) {
  87876. serializationObject.geometries = {};
  87877. serializationObject.geometries.boxes = [];
  87878. serializationObject.geometries.spheres = [];
  87879. serializationObject.geometries.cylinders = [];
  87880. serializationObject.geometries.toruses = [];
  87881. serializationObject.geometries.grounds = [];
  87882. serializationObject.geometries.planes = [];
  87883. serializationObject.geometries.torusKnots = [];
  87884. serializationObject.geometries.vertexData = [];
  87885. }
  87886. serializeGeometry(geometry, serializationObject.geometries);
  87887. }
  87888. // Skeletons
  87889. if (mesh.skeleton) {
  87890. serializationObject.skeletons = serializationObject.skeletons || [];
  87891. serializationObject.skeletons.push(mesh.skeleton.serialize());
  87892. }
  87893. //serialize the actual mesh
  87894. serializationObject.meshes = serializationObject.meshes || [];
  87895. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  87896. }
  87897. };
  87898. var SceneSerializer = /** @class */ (function () {
  87899. function SceneSerializer() {
  87900. }
  87901. SceneSerializer.ClearCache = function () {
  87902. serializedGeometries = [];
  87903. };
  87904. SceneSerializer.Serialize = function (scene) {
  87905. var serializationObject = {};
  87906. SceneSerializer.ClearCache();
  87907. // Scene
  87908. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  87909. serializationObject.autoClear = scene.autoClear;
  87910. serializationObject.clearColor = scene.clearColor.asArray();
  87911. serializationObject.ambientColor = scene.ambientColor.asArray();
  87912. serializationObject.gravity = scene.gravity.asArray();
  87913. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  87914. serializationObject.workerCollisions = scene.workerCollisions;
  87915. // Fog
  87916. if (scene.fogMode && scene.fogMode !== 0) {
  87917. serializationObject.fogMode = scene.fogMode;
  87918. serializationObject.fogColor = scene.fogColor.asArray();
  87919. serializationObject.fogStart = scene.fogStart;
  87920. serializationObject.fogEnd = scene.fogEnd;
  87921. serializationObject.fogDensity = scene.fogDensity;
  87922. }
  87923. //Physics
  87924. if (scene.isPhysicsEnabled()) {
  87925. var physicEngine = scene.getPhysicsEngine();
  87926. if (physicEngine) {
  87927. serializationObject.physicsEnabled = true;
  87928. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  87929. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  87930. }
  87931. }
  87932. // Metadata
  87933. if (scene.metadata) {
  87934. serializationObject.metadata = scene.metadata;
  87935. }
  87936. // Morph targets
  87937. serializationObject.morphTargetManagers = [];
  87938. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  87939. var abstractMesh = _a[_i];
  87940. var manager = abstractMesh.morphTargetManager;
  87941. if (manager) {
  87942. serializationObject.morphTargetManagers.push(manager.serialize());
  87943. }
  87944. }
  87945. // Lights
  87946. serializationObject.lights = [];
  87947. var index;
  87948. var light;
  87949. for (index = 0; index < scene.lights.length; index++) {
  87950. light = scene.lights[index];
  87951. if (!light.doNotSerialize) {
  87952. serializationObject.lights.push(light.serialize());
  87953. }
  87954. }
  87955. // Cameras
  87956. serializationObject.cameras = [];
  87957. for (index = 0; index < scene.cameras.length; index++) {
  87958. var camera = scene.cameras[index];
  87959. if (!camera.doNotSerialize) {
  87960. serializationObject.cameras.push(camera.serialize());
  87961. }
  87962. }
  87963. if (scene.activeCamera) {
  87964. serializationObject.activeCameraID = scene.activeCamera.id;
  87965. }
  87966. // Animations
  87967. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  87968. // Materials
  87969. serializationObject.materials = [];
  87970. serializationObject.multiMaterials = [];
  87971. var material;
  87972. for (index = 0; index < scene.materials.length; index++) {
  87973. material = scene.materials[index];
  87974. if (!material.doNotSerialize) {
  87975. serializationObject.materials.push(material.serialize());
  87976. }
  87977. }
  87978. // MultiMaterials
  87979. serializationObject.multiMaterials = [];
  87980. for (index = 0; index < scene.multiMaterials.length; index++) {
  87981. var multiMaterial = scene.multiMaterials[index];
  87982. serializationObject.multiMaterials.push(multiMaterial.serialize());
  87983. }
  87984. // Environment texture
  87985. if (scene.environmentTexture) {
  87986. serializationObject.environmentTexture = scene.environmentTexture.name;
  87987. }
  87988. // Skeletons
  87989. serializationObject.skeletons = [];
  87990. for (index = 0; index < scene.skeletons.length; index++) {
  87991. var skeleton = scene.skeletons[index];
  87992. if (!skeleton.doNotSerialize) {
  87993. serializationObject.skeletons.push(skeleton.serialize());
  87994. }
  87995. }
  87996. // Transform nodes
  87997. serializationObject.transformNodes = [];
  87998. for (index = 0; index < scene.transformNodes.length; index++) {
  87999. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  88000. }
  88001. // Geometries
  88002. serializationObject.geometries = {};
  88003. serializationObject.geometries.boxes = [];
  88004. serializationObject.geometries.spheres = [];
  88005. serializationObject.geometries.cylinders = [];
  88006. serializationObject.geometries.toruses = [];
  88007. serializationObject.geometries.grounds = [];
  88008. serializationObject.geometries.planes = [];
  88009. serializationObject.geometries.torusKnots = [];
  88010. serializationObject.geometries.vertexData = [];
  88011. serializedGeometries = [];
  88012. var geometries = scene.getGeometries();
  88013. for (index = 0; index < geometries.length; index++) {
  88014. var geometry = geometries[index];
  88015. if (geometry.isReady()) {
  88016. serializeGeometry(geometry, serializationObject.geometries);
  88017. }
  88018. }
  88019. // Meshes
  88020. serializationObject.meshes = [];
  88021. for (index = 0; index < scene.meshes.length; index++) {
  88022. var abstractMesh = scene.meshes[index];
  88023. if (abstractMesh instanceof BABYLON.Mesh) {
  88024. var mesh = abstractMesh;
  88025. if (!mesh.doNotSerialize) {
  88026. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  88027. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  88028. }
  88029. }
  88030. }
  88031. }
  88032. // Particles Systems
  88033. serializationObject.particleSystems = [];
  88034. for (index = 0; index < scene.particleSystems.length; index++) {
  88035. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  88036. }
  88037. // Lens flares
  88038. serializationObject.lensFlareSystems = [];
  88039. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  88040. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  88041. }
  88042. // Shadows
  88043. serializationObject.shadowGenerators = [];
  88044. for (index = 0; index < scene.lights.length; index++) {
  88045. light = scene.lights[index];
  88046. var shadowGenerator = light.getShadowGenerator();
  88047. if (shadowGenerator) {
  88048. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  88049. }
  88050. }
  88051. // Action Manager
  88052. if (scene.actionManager) {
  88053. serializationObject.actions = scene.actionManager.serialize("scene");
  88054. }
  88055. // Audio
  88056. serializationObject.sounds = [];
  88057. for (index = 0; index < scene.soundTracks.length; index++) {
  88058. var soundtrack = scene.soundTracks[index];
  88059. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  88060. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  88061. }
  88062. }
  88063. return serializationObject;
  88064. };
  88065. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  88066. if (withParents === void 0) { withParents = false; }
  88067. if (withChildren === void 0) { withChildren = false; }
  88068. var serializationObject = {};
  88069. SceneSerializer.ClearCache();
  88070. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  88071. if (withParents || withChildren) {
  88072. //deliberate for loop! not for each, appended should be processed as well.
  88073. for (var i = 0; i < toSerialize.length; ++i) {
  88074. if (withChildren) {
  88075. toSerialize[i].getDescendants().forEach(function (node) {
  88076. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  88077. toSerialize.push(node);
  88078. }
  88079. });
  88080. }
  88081. //make sure the array doesn't contain the object already
  88082. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  88083. toSerialize.push(toSerialize[i].parent);
  88084. }
  88085. }
  88086. }
  88087. toSerialize.forEach(function (mesh) {
  88088. finalizeSingleMesh(mesh, serializationObject);
  88089. });
  88090. return serializationObject;
  88091. };
  88092. return SceneSerializer;
  88093. }());
  88094. BABYLON.SceneSerializer = SceneSerializer;
  88095. })(BABYLON || (BABYLON = {}));
  88096. //# sourceMappingURL=babylon.sceneSerializer.js.map
  88097. var BABYLON;
  88098. (function (BABYLON) {
  88099. var ReflectionProbe = /** @class */ (function () {
  88100. function ReflectionProbe(name, size, scene, generateMipMaps) {
  88101. if (generateMipMaps === void 0) { generateMipMaps = true; }
  88102. var _this = this;
  88103. this.name = name;
  88104. this._viewMatrix = BABYLON.Matrix.Identity();
  88105. this._target = BABYLON.Vector3.Zero();
  88106. this._add = BABYLON.Vector3.Zero();
  88107. this._invertYAxis = false;
  88108. this.position = BABYLON.Vector3.Zero();
  88109. this._scene = scene;
  88110. this._scene.reflectionProbes.push(this);
  88111. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  88112. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  88113. switch (faceIndex) {
  88114. case 0:
  88115. _this._add.copyFromFloats(1, 0, 0);
  88116. break;
  88117. case 1:
  88118. _this._add.copyFromFloats(-1, 0, 0);
  88119. break;
  88120. case 2:
  88121. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  88122. break;
  88123. case 3:
  88124. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  88125. break;
  88126. case 4:
  88127. _this._add.copyFromFloats(0, 0, 1);
  88128. break;
  88129. case 5:
  88130. _this._add.copyFromFloats(0, 0, -1);
  88131. break;
  88132. }
  88133. if (_this._attachedMesh) {
  88134. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  88135. }
  88136. _this.position.addToRef(_this._add, _this._target);
  88137. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  88138. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  88139. scene._forcedViewPosition = _this.position;
  88140. });
  88141. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  88142. scene._forcedViewPosition = null;
  88143. scene.updateTransformMatrix(true);
  88144. });
  88145. if (scene.activeCamera) {
  88146. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  88147. }
  88148. }
  88149. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  88150. get: function () {
  88151. return this._renderTargetTexture.samples;
  88152. },
  88153. set: function (value) {
  88154. this._renderTargetTexture.samples = value;
  88155. },
  88156. enumerable: true,
  88157. configurable: true
  88158. });
  88159. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  88160. get: function () {
  88161. return this._renderTargetTexture.refreshRate;
  88162. },
  88163. set: function (value) {
  88164. this._renderTargetTexture.refreshRate = value;
  88165. },
  88166. enumerable: true,
  88167. configurable: true
  88168. });
  88169. ReflectionProbe.prototype.getScene = function () {
  88170. return this._scene;
  88171. };
  88172. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  88173. get: function () {
  88174. return this._renderTargetTexture;
  88175. },
  88176. enumerable: true,
  88177. configurable: true
  88178. });
  88179. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  88180. get: function () {
  88181. return this._renderTargetTexture.renderList;
  88182. },
  88183. enumerable: true,
  88184. configurable: true
  88185. });
  88186. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  88187. this._attachedMesh = mesh;
  88188. };
  88189. /**
  88190. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  88191. *
  88192. * @param renderingGroupId The rendering group id corresponding to its index
  88193. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  88194. */
  88195. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  88196. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  88197. };
  88198. ReflectionProbe.prototype.dispose = function () {
  88199. var index = this._scene.reflectionProbes.indexOf(this);
  88200. if (index !== -1) {
  88201. // Remove from the scene if found
  88202. this._scene.reflectionProbes.splice(index, 1);
  88203. }
  88204. if (this._renderTargetTexture) {
  88205. this._renderTargetTexture.dispose();
  88206. this._renderTargetTexture = null;
  88207. }
  88208. };
  88209. return ReflectionProbe;
  88210. }());
  88211. BABYLON.ReflectionProbe = ReflectionProbe;
  88212. })(BABYLON || (BABYLON = {}));
  88213. //# sourceMappingURL=babylon.reflectionProbe.js.map
  88214. var BABYLON;
  88215. (function (BABYLON) {
  88216. var Layer = /** @class */ (function () {
  88217. function Layer(name, imgUrl, scene, isBackground, color) {
  88218. this.name = name;
  88219. this.scale = new BABYLON.Vector2(1, 1);
  88220. this.offset = new BABYLON.Vector2(0, 0);
  88221. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  88222. this.layerMask = 0x0FFFFFFF;
  88223. this._vertexBuffers = {};
  88224. // Events
  88225. /**
  88226. * An event triggered when the layer is disposed.
  88227. * @type {BABYLON.Observable}
  88228. */
  88229. this.onDisposeObservable = new BABYLON.Observable();
  88230. /**
  88231. * An event triggered before rendering the scene
  88232. * @type {BABYLON.Observable}
  88233. */
  88234. this.onBeforeRenderObservable = new BABYLON.Observable();
  88235. /**
  88236. * An event triggered after rendering the scene
  88237. * @type {BABYLON.Observable}
  88238. */
  88239. this.onAfterRenderObservable = new BABYLON.Observable();
  88240. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  88241. this.isBackground = isBackground === undefined ? true : isBackground;
  88242. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  88243. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  88244. this._scene.layers.push(this);
  88245. var engine = this._scene.getEngine();
  88246. // VBO
  88247. var vertices = [];
  88248. vertices.push(1, 1);
  88249. vertices.push(-1, 1);
  88250. vertices.push(-1, -1);
  88251. vertices.push(1, -1);
  88252. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  88253. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  88254. this._createIndexBuffer();
  88255. // Effects
  88256. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  88257. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  88258. }
  88259. Object.defineProperty(Layer.prototype, "onDispose", {
  88260. set: function (callback) {
  88261. if (this._onDisposeObserver) {
  88262. this.onDisposeObservable.remove(this._onDisposeObserver);
  88263. }
  88264. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  88265. },
  88266. enumerable: true,
  88267. configurable: true
  88268. });
  88269. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  88270. set: function (callback) {
  88271. if (this._onBeforeRenderObserver) {
  88272. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  88273. }
  88274. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  88275. },
  88276. enumerable: true,
  88277. configurable: true
  88278. });
  88279. Object.defineProperty(Layer.prototype, "onAfterRender", {
  88280. set: function (callback) {
  88281. if (this._onAfterRenderObserver) {
  88282. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  88283. }
  88284. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  88285. },
  88286. enumerable: true,
  88287. configurable: true
  88288. });
  88289. Layer.prototype._createIndexBuffer = function () {
  88290. var engine = this._scene.getEngine();
  88291. // Indices
  88292. var indices = [];
  88293. indices.push(0);
  88294. indices.push(1);
  88295. indices.push(2);
  88296. indices.push(0);
  88297. indices.push(2);
  88298. indices.push(3);
  88299. this._indexBuffer = engine.createIndexBuffer(indices);
  88300. };
  88301. Layer.prototype._rebuild = function () {
  88302. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88303. if (vb) {
  88304. vb._rebuild();
  88305. }
  88306. this._createIndexBuffer();
  88307. };
  88308. Layer.prototype.render = function () {
  88309. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  88310. // Check
  88311. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  88312. return;
  88313. var engine = this._scene.getEngine();
  88314. this.onBeforeRenderObservable.notifyObservers(this);
  88315. // Render
  88316. engine.enableEffect(currentEffect);
  88317. engine.setState(false);
  88318. // Texture
  88319. currentEffect.setTexture("textureSampler", this.texture);
  88320. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  88321. // Color
  88322. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  88323. // Scale / offset
  88324. currentEffect.setVector2("offset", this.offset);
  88325. currentEffect.setVector2("scale", this.scale);
  88326. // VBOs
  88327. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  88328. // Draw order
  88329. if (!this.alphaTest) {
  88330. engine.setAlphaMode(this.alphaBlendingMode);
  88331. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  88332. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  88333. }
  88334. else {
  88335. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  88336. }
  88337. this.onAfterRenderObservable.notifyObservers(this);
  88338. };
  88339. Layer.prototype.dispose = function () {
  88340. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88341. if (vertexBuffer) {
  88342. vertexBuffer.dispose();
  88343. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  88344. }
  88345. if (this._indexBuffer) {
  88346. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  88347. this._indexBuffer = null;
  88348. }
  88349. if (this.texture) {
  88350. this.texture.dispose();
  88351. this.texture = null;
  88352. }
  88353. // Remove from scene
  88354. var index = this._scene.layers.indexOf(this);
  88355. this._scene.layers.splice(index, 1);
  88356. // Callback
  88357. this.onDisposeObservable.notifyObservers(this);
  88358. this.onDisposeObservable.clear();
  88359. this.onAfterRenderObservable.clear();
  88360. this.onBeforeRenderObservable.clear();
  88361. };
  88362. return Layer;
  88363. }());
  88364. BABYLON.Layer = Layer;
  88365. })(BABYLON || (BABYLON = {}));
  88366. //# sourceMappingURL=babylon.layer.js.map
  88367. var BABYLON;
  88368. (function (BABYLON) {
  88369. var TextureTools = /** @class */ (function () {
  88370. function TextureTools() {
  88371. }
  88372. /**
  88373. * Uses the GPU to create a copy texture rescaled at a given size
  88374. * @param texture Texture to copy from
  88375. * @param width Desired width
  88376. * @param height Desired height
  88377. * @return Generated texture
  88378. */
  88379. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  88380. if (useBilinearMode === void 0) { useBilinearMode = true; }
  88381. var scene = texture.getScene();
  88382. var engine = scene.getEngine();
  88383. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  88384. rtt.wrapU = texture.wrapU;
  88385. rtt.wrapV = texture.wrapV;
  88386. rtt.uOffset = texture.uOffset;
  88387. rtt.vOffset = texture.vOffset;
  88388. rtt.uScale = texture.uScale;
  88389. rtt.vScale = texture.vScale;
  88390. rtt.uAng = texture.uAng;
  88391. rtt.vAng = texture.vAng;
  88392. rtt.wAng = texture.wAng;
  88393. rtt.coordinatesIndex = texture.coordinatesIndex;
  88394. rtt.level = texture.level;
  88395. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  88396. rtt._texture.isReady = false;
  88397. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88398. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88399. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  88400. passPostProcess.getEffect().executeWhenCompiled(function () {
  88401. passPostProcess.onApply = function (effect) {
  88402. effect.setTexture("textureSampler", texture);
  88403. };
  88404. var internalTexture = rtt.getInternalTexture();
  88405. if (internalTexture) {
  88406. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  88407. engine.unBindFramebuffer(internalTexture);
  88408. rtt.disposeFramebufferObjects();
  88409. passPostProcess.dispose();
  88410. internalTexture.isReady = true;
  88411. }
  88412. });
  88413. return rtt;
  88414. };
  88415. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  88416. if (!scene._environmentBRDFTexture) {
  88417. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  88418. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88419. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88420. scene._environmentBRDFTexture = texture;
  88421. }
  88422. return scene._environmentBRDFTexture;
  88423. };
  88424. 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=";
  88425. return TextureTools;
  88426. }());
  88427. BABYLON.TextureTools = TextureTools;
  88428. })(BABYLON || (BABYLON = {}));
  88429. //# sourceMappingURL=babylon.textureTools.js.map
  88430. var BABYLON;
  88431. (function (BABYLON) {
  88432. var FramingBehavior = /** @class */ (function () {
  88433. function FramingBehavior() {
  88434. this._mode = FramingBehavior.FitFrustumSidesMode;
  88435. this._radiusScale = 1.0;
  88436. this._positionScale = 0.5;
  88437. this._defaultElevation = 0.3;
  88438. this._elevationReturnTime = 1500;
  88439. this._elevationReturnWaitTime = 1000;
  88440. this._zoomStopsAnimation = false;
  88441. this._framingTime = 1500;
  88442. this._isPointerDown = false;
  88443. this._lastInteractionTime = -Infinity;
  88444. // Framing control
  88445. this._animatables = new Array();
  88446. this._betaIsAnimating = false;
  88447. }
  88448. Object.defineProperty(FramingBehavior.prototype, "name", {
  88449. get: function () {
  88450. return "Framing";
  88451. },
  88452. enumerable: true,
  88453. configurable: true
  88454. });
  88455. Object.defineProperty(FramingBehavior.prototype, "mode", {
  88456. /**
  88457. * Gets current mode used by the behavior.
  88458. */
  88459. get: function () {
  88460. return this._mode;
  88461. },
  88462. /**
  88463. * Sets the current mode used by the behavior
  88464. */
  88465. set: function (mode) {
  88466. this._mode = mode;
  88467. },
  88468. enumerable: true,
  88469. configurable: true
  88470. });
  88471. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  88472. /**
  88473. * Gets the scale applied to the radius
  88474. */
  88475. get: function () {
  88476. return this._radiusScale;
  88477. },
  88478. /**
  88479. * Sets the scale applied to the radius (1 by default)
  88480. */
  88481. set: function (radius) {
  88482. this._radiusScale = radius;
  88483. },
  88484. enumerable: true,
  88485. configurable: true
  88486. });
  88487. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  88488. /**
  88489. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  88490. */
  88491. get: function () {
  88492. return this._positionScale;
  88493. },
  88494. /**
  88495. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  88496. */
  88497. set: function (scale) {
  88498. this._positionScale = scale;
  88499. },
  88500. enumerable: true,
  88501. configurable: true
  88502. });
  88503. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  88504. /**
  88505. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  88506. * behaviour is triggered, in radians.
  88507. */
  88508. get: function () {
  88509. return this._defaultElevation;
  88510. },
  88511. /**
  88512. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  88513. * behaviour is triggered, in radians.
  88514. */
  88515. set: function (elevation) {
  88516. this._defaultElevation = elevation;
  88517. },
  88518. enumerable: true,
  88519. configurable: true
  88520. });
  88521. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  88522. /**
  88523. * Gets the time (in milliseconds) taken to return to the default beta position.
  88524. * Negative value indicates camera should not return to default.
  88525. */
  88526. get: function () {
  88527. return this._elevationReturnTime;
  88528. },
  88529. /**
  88530. * Sets the time (in milliseconds) taken to return to the default beta position.
  88531. * Negative value indicates camera should not return to default.
  88532. */
  88533. set: function (speed) {
  88534. this._elevationReturnTime = speed;
  88535. },
  88536. enumerable: true,
  88537. configurable: true
  88538. });
  88539. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  88540. /**
  88541. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  88542. */
  88543. get: function () {
  88544. return this._elevationReturnWaitTime;
  88545. },
  88546. /**
  88547. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  88548. */
  88549. set: function (time) {
  88550. this._elevationReturnWaitTime = time;
  88551. },
  88552. enumerable: true,
  88553. configurable: true
  88554. });
  88555. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  88556. /**
  88557. * Gets the flag that indicates if user zooming should stop animation.
  88558. */
  88559. get: function () {
  88560. return this._zoomStopsAnimation;
  88561. },
  88562. /**
  88563. * Sets the flag that indicates if user zooming should stop animation.
  88564. */
  88565. set: function (flag) {
  88566. this._zoomStopsAnimation = flag;
  88567. },
  88568. enumerable: true,
  88569. configurable: true
  88570. });
  88571. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  88572. /**
  88573. * Gets the transition time when framing the mesh, in milliseconds
  88574. */
  88575. get: function () {
  88576. return this._framingTime;
  88577. },
  88578. /**
  88579. * Sets the transition time when framing the mesh, in milliseconds
  88580. */
  88581. set: function (time) {
  88582. this._framingTime = time;
  88583. },
  88584. enumerable: true,
  88585. configurable: true
  88586. });
  88587. FramingBehavior.prototype.init = function () {
  88588. // Do notihng
  88589. };
  88590. FramingBehavior.prototype.attach = function (camera) {
  88591. var _this = this;
  88592. this._attachedCamera = camera;
  88593. var scene = this._attachedCamera.getScene();
  88594. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  88595. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  88596. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  88597. _this._isPointerDown = true;
  88598. return;
  88599. }
  88600. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  88601. _this._isPointerDown = false;
  88602. }
  88603. });
  88604. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  88605. if (mesh) {
  88606. _this.zoomOnMesh(mesh);
  88607. }
  88608. });
  88609. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  88610. // Stop the animation if there is user interaction and the animation should stop for this interaction
  88611. _this._applyUserInteraction();
  88612. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  88613. // back to the default position after a given timeout
  88614. _this._maintainCameraAboveGround();
  88615. });
  88616. };
  88617. FramingBehavior.prototype.detach = function () {
  88618. if (!this._attachedCamera) {
  88619. return;
  88620. }
  88621. var scene = this._attachedCamera.getScene();
  88622. if (this._onPrePointerObservableObserver) {
  88623. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  88624. }
  88625. if (this._onAfterCheckInputsObserver) {
  88626. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  88627. }
  88628. if (this._onMeshTargetChangedObserver) {
  88629. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  88630. }
  88631. this._attachedCamera = null;
  88632. };
  88633. /**
  88634. * Targets the given mesh and updates zoom level accordingly.
  88635. * @param mesh The mesh to target.
  88636. * @param radius Optional. If a cached radius position already exists, overrides default.
  88637. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88638. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88639. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88640. */
  88641. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  88642. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88643. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88644. mesh.computeWorldMatrix(true);
  88645. var boundingBox = mesh.getBoundingInfo().boundingBox;
  88646. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  88647. };
  88648. /**
  88649. * Targets the given mesh with its children and updates zoom level accordingly.
  88650. * @param mesh The mesh to target.
  88651. * @param radius Optional. If a cached radius position already exists, overrides default.
  88652. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88653. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88654. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88655. */
  88656. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  88657. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88658. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88659. mesh.computeWorldMatrix(true);
  88660. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  88661. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  88662. };
  88663. /**
  88664. * Targets the given meshes with their children and updates zoom level accordingly.
  88665. * @param meshes The mesh to target.
  88666. * @param radius Optional. If a cached radius position already exists, overrides default.
  88667. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88668. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88669. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88670. */
  88671. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  88672. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88673. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88674. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  88675. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  88676. for (var i = 0; i < meshes.length; i++) {
  88677. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  88678. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  88679. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  88680. }
  88681. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  88682. };
  88683. /**
  88684. * Targets the given mesh and updates zoom level accordingly.
  88685. * @param mesh The mesh to target.
  88686. * @param radius Optional. If a cached radius position already exists, overrides default.
  88687. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88688. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88689. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88690. */
  88691. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  88692. var _this = this;
  88693. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88694. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88695. var zoomTarget;
  88696. if (!this._attachedCamera) {
  88697. return;
  88698. }
  88699. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  88700. var bottom = minimumWorld.y;
  88701. var top = maximumWorld.y;
  88702. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  88703. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  88704. if (focusOnOriginXZ) {
  88705. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  88706. }
  88707. else {
  88708. var centerWorld = minimumWorld.add(radiusWorld);
  88709. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  88710. }
  88711. if (!this._vectorTransition) {
  88712. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  88713. }
  88714. this._betaIsAnimating = true;
  88715. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  88716. if (animatable) {
  88717. this._animatables.push(animatable);
  88718. }
  88719. // sets the radius and lower radius bounds
  88720. // Small delta ensures camera is not always at lower zoom limit.
  88721. var radius = 0;
  88722. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  88723. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  88724. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  88725. radius = position;
  88726. }
  88727. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  88728. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  88729. if (this._attachedCamera.lowerRadiusLimit === null) {
  88730. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  88731. }
  88732. }
  88733. // Set sensibilities
  88734. var extend = maximumWorld.subtract(minimumWorld).length();
  88735. this._attachedCamera.panningSensibility = 5000 / extend;
  88736. this._attachedCamera.wheelPrecision = 100 / radius;
  88737. // transition to new radius
  88738. if (!this._radiusTransition) {
  88739. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  88740. }
  88741. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  88742. _this.stopAllAnimations();
  88743. if (onAnimationEnd) {
  88744. onAnimationEnd();
  88745. }
  88746. if (_this._attachedCamera) {
  88747. _this._attachedCamera.storeState();
  88748. }
  88749. });
  88750. if (animatable) {
  88751. this._animatables.push(animatable);
  88752. }
  88753. };
  88754. /**
  88755. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  88756. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  88757. * frustum width.
  88758. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  88759. * to fully enclose the mesh in the viewing frustum.
  88760. */
  88761. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  88762. var size = maximumWorld.subtract(minimumWorld);
  88763. var boxVectorGlobalDiagonal = size.length();
  88764. var frustumSlope = this._getFrustumSlope();
  88765. // Formula for setting distance
  88766. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  88767. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  88768. // Horizon distance
  88769. var radius = radiusWithoutFraming * this._radiusScale;
  88770. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  88771. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  88772. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  88773. var camera = this._attachedCamera;
  88774. if (!camera) {
  88775. return 0;
  88776. }
  88777. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  88778. // Don't exceed the requested limit
  88779. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  88780. }
  88781. // Don't exceed the upper radius limit
  88782. if (camera.upperRadiusLimit) {
  88783. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  88784. }
  88785. return distance;
  88786. };
  88787. /**
  88788. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  88789. * is automatically returned to its default position (expected to be above ground plane).
  88790. */
  88791. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  88792. var _this = this;
  88793. if (this._elevationReturnTime < 0) {
  88794. return;
  88795. }
  88796. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  88797. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  88798. var limitBeta = Math.PI * 0.5;
  88799. // Bring the camera back up if below the ground plane
  88800. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  88801. this._betaIsAnimating = true;
  88802. //Transition to new position
  88803. this.stopAllAnimations();
  88804. if (!this._betaTransition) {
  88805. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  88806. }
  88807. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  88808. _this._clearAnimationLocks();
  88809. _this.stopAllAnimations();
  88810. });
  88811. if (animatabe) {
  88812. this._animatables.push(animatabe);
  88813. }
  88814. }
  88815. };
  88816. /**
  88817. * Returns the frustum slope based on the canvas ratio and camera FOV
  88818. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  88819. */
  88820. FramingBehavior.prototype._getFrustumSlope = function () {
  88821. // Calculate the viewport ratio
  88822. // Aspect Ratio is Height/Width.
  88823. var camera = this._attachedCamera;
  88824. if (!camera) {
  88825. return BABYLON.Vector2.Zero();
  88826. }
  88827. var engine = camera.getScene().getEngine();
  88828. var aspectRatio = engine.getAspectRatio(camera);
  88829. // Camera FOV is the vertical field of view (top-bottom) in radians.
  88830. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  88831. var frustumSlopeY = Math.tan(camera.fov / 2);
  88832. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  88833. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  88834. // along the forward vector.
  88835. var frustumSlopeX = frustumSlopeY * aspectRatio;
  88836. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  88837. };
  88838. /**
  88839. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  88840. */
  88841. FramingBehavior.prototype._clearAnimationLocks = function () {
  88842. this._betaIsAnimating = false;
  88843. };
  88844. /**
  88845. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  88846. */
  88847. FramingBehavior.prototype._applyUserInteraction = function () {
  88848. if (this.isUserIsMoving) {
  88849. this._lastInteractionTime = BABYLON.Tools.Now;
  88850. this.stopAllAnimations();
  88851. this._clearAnimationLocks();
  88852. }
  88853. };
  88854. /**
  88855. * Stops and removes all animations that have been applied to the camera
  88856. */
  88857. FramingBehavior.prototype.stopAllAnimations = function () {
  88858. if (this._attachedCamera) {
  88859. this._attachedCamera.animations = [];
  88860. }
  88861. while (this._animatables.length) {
  88862. if (this._animatables[0]) {
  88863. this._animatables[0].onAnimationEnd = null;
  88864. this._animatables[0].stop();
  88865. }
  88866. this._animatables.shift();
  88867. }
  88868. };
  88869. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  88870. /**
  88871. * Gets a value indicating if the user is moving the camera
  88872. */
  88873. get: function () {
  88874. if (!this._attachedCamera) {
  88875. return false;
  88876. }
  88877. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  88878. this._attachedCamera.inertialBetaOffset !== 0 ||
  88879. this._attachedCamera.inertialRadiusOffset !== 0 ||
  88880. this._attachedCamera.inertialPanningX !== 0 ||
  88881. this._attachedCamera.inertialPanningY !== 0 ||
  88882. this._isPointerDown;
  88883. },
  88884. enumerable: true,
  88885. configurable: true
  88886. });
  88887. /**
  88888. * The easing function used by animations
  88889. */
  88890. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  88891. /**
  88892. * The easing mode used by animations
  88893. */
  88894. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  88895. // Statics
  88896. /**
  88897. * The camera can move all the way towards the mesh.
  88898. */
  88899. FramingBehavior.IgnoreBoundsSizeMode = 0;
  88900. /**
  88901. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  88902. */
  88903. FramingBehavior.FitFrustumSidesMode = 1;
  88904. return FramingBehavior;
  88905. }());
  88906. BABYLON.FramingBehavior = FramingBehavior;
  88907. })(BABYLON || (BABYLON = {}));
  88908. //# sourceMappingURL=babylon.framingBehavior.js.map
  88909. var BABYLON;
  88910. (function (BABYLON) {
  88911. /**
  88912. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  88913. */
  88914. var BouncingBehavior = /** @class */ (function () {
  88915. function BouncingBehavior() {
  88916. /**
  88917. * The duration of the animation, in milliseconds
  88918. */
  88919. this.transitionDuration = 450;
  88920. /**
  88921. * Length of the distance animated by the transition when lower radius is reached
  88922. */
  88923. this.lowerRadiusTransitionRange = 2;
  88924. /**
  88925. * Length of the distance animated by the transition when upper radius is reached
  88926. */
  88927. this.upperRadiusTransitionRange = -2;
  88928. this._autoTransitionRange = false;
  88929. // Animations
  88930. this._radiusIsAnimating = false;
  88931. this._radiusBounceTransition = null;
  88932. this._animatables = new Array();
  88933. }
  88934. Object.defineProperty(BouncingBehavior.prototype, "name", {
  88935. get: function () {
  88936. return "Bouncing";
  88937. },
  88938. enumerable: true,
  88939. configurable: true
  88940. });
  88941. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  88942. /**
  88943. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  88944. */
  88945. get: function () {
  88946. return this._autoTransitionRange;
  88947. },
  88948. /**
  88949. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  88950. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  88951. */
  88952. set: function (value) {
  88953. var _this = this;
  88954. if (this._autoTransitionRange === value) {
  88955. return;
  88956. }
  88957. this._autoTransitionRange = value;
  88958. var camera = this._attachedCamera;
  88959. if (!camera) {
  88960. return;
  88961. }
  88962. if (value) {
  88963. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  88964. if (!mesh) {
  88965. return;
  88966. }
  88967. mesh.computeWorldMatrix(true);
  88968. var diagonal = mesh.getBoundingInfo().diagonalLength;
  88969. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  88970. _this.upperRadiusTransitionRange = diagonal * 0.05;
  88971. });
  88972. }
  88973. else if (this._onMeshTargetChangedObserver) {
  88974. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  88975. }
  88976. },
  88977. enumerable: true,
  88978. configurable: true
  88979. });
  88980. BouncingBehavior.prototype.init = function () {
  88981. // Do notihng
  88982. };
  88983. BouncingBehavior.prototype.attach = function (camera) {
  88984. var _this = this;
  88985. this._attachedCamera = camera;
  88986. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  88987. if (!_this._attachedCamera) {
  88988. return;
  88989. }
  88990. // Add the bounce animation to the lower radius limit
  88991. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  88992. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  88993. }
  88994. // Add the bounce animation to the upper radius limit
  88995. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  88996. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  88997. }
  88998. });
  88999. };
  89000. BouncingBehavior.prototype.detach = function () {
  89001. if (!this._attachedCamera) {
  89002. return;
  89003. }
  89004. if (this._onAfterCheckInputsObserver) {
  89005. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89006. }
  89007. if (this._onMeshTargetChangedObserver) {
  89008. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89009. }
  89010. this._attachedCamera = null;
  89011. };
  89012. /**
  89013. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  89014. * @param radiusLimit The limit to check against.
  89015. * @return Bool to indicate if at limit.
  89016. */
  89017. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  89018. if (!this._attachedCamera) {
  89019. return false;
  89020. }
  89021. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  89022. return true;
  89023. }
  89024. return false;
  89025. };
  89026. /**
  89027. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  89028. * @param radiusDelta The delta by which to animate to. Can be negative.
  89029. */
  89030. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  89031. var _this = this;
  89032. if (!this._attachedCamera) {
  89033. return;
  89034. }
  89035. if (!this._radiusBounceTransition) {
  89036. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  89037. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  89038. }
  89039. // Prevent zoom until bounce has completed
  89040. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  89041. this._attachedCamera.wheelPrecision = Infinity;
  89042. this._attachedCamera.inertialRadiusOffset = 0;
  89043. // Animate to the radius limit
  89044. this.stopAllAnimations();
  89045. this._radiusIsAnimating = true;
  89046. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  89047. if (animatable) {
  89048. this._animatables.push(animatable);
  89049. }
  89050. };
  89051. /**
  89052. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  89053. */
  89054. BouncingBehavior.prototype._clearAnimationLocks = function () {
  89055. this._radiusIsAnimating = false;
  89056. if (this._attachedCamera) {
  89057. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  89058. }
  89059. };
  89060. /**
  89061. * Stops and removes all animations that have been applied to the camera
  89062. */
  89063. BouncingBehavior.prototype.stopAllAnimations = function () {
  89064. if (this._attachedCamera) {
  89065. this._attachedCamera.animations = [];
  89066. }
  89067. while (this._animatables.length) {
  89068. this._animatables[0].onAnimationEnd = null;
  89069. this._animatables[0].stop();
  89070. this._animatables.shift();
  89071. }
  89072. };
  89073. /**
  89074. * The easing function used by animations
  89075. */
  89076. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  89077. /**
  89078. * The easing mode used by animations
  89079. */
  89080. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  89081. return BouncingBehavior;
  89082. }());
  89083. BABYLON.BouncingBehavior = BouncingBehavior;
  89084. })(BABYLON || (BABYLON = {}));
  89085. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  89086. var BABYLON;
  89087. (function (BABYLON) {
  89088. var AutoRotationBehavior = /** @class */ (function () {
  89089. function AutoRotationBehavior() {
  89090. this._zoomStopsAnimation = false;
  89091. this._idleRotationSpeed = 0.05;
  89092. this._idleRotationWaitTime = 2000;
  89093. this._idleRotationSpinupTime = 2000;
  89094. this._isPointerDown = false;
  89095. this._lastFrameTime = null;
  89096. this._lastInteractionTime = -Infinity;
  89097. this._cameraRotationSpeed = 0;
  89098. this._lastFrameRadius = 0;
  89099. }
  89100. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  89101. get: function () {
  89102. return "AutoRotation";
  89103. },
  89104. enumerable: true,
  89105. configurable: true
  89106. });
  89107. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  89108. /**
  89109. * Gets the flag that indicates if user zooming should stop animation.
  89110. */
  89111. get: function () {
  89112. return this._zoomStopsAnimation;
  89113. },
  89114. /**
  89115. * Sets the flag that indicates if user zooming should stop animation.
  89116. */
  89117. set: function (flag) {
  89118. this._zoomStopsAnimation = flag;
  89119. },
  89120. enumerable: true,
  89121. configurable: true
  89122. });
  89123. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  89124. /**
  89125. * Gets the default speed at which the camera rotates around the model.
  89126. */
  89127. get: function () {
  89128. return this._idleRotationSpeed;
  89129. },
  89130. /**
  89131. * Sets the default speed at which the camera rotates around the model.
  89132. */
  89133. set: function (speed) {
  89134. this._idleRotationSpeed = speed;
  89135. },
  89136. enumerable: true,
  89137. configurable: true
  89138. });
  89139. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  89140. /**
  89141. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  89142. */
  89143. get: function () {
  89144. return this._idleRotationWaitTime;
  89145. },
  89146. /**
  89147. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  89148. */
  89149. set: function (time) {
  89150. this._idleRotationWaitTime = time;
  89151. },
  89152. enumerable: true,
  89153. configurable: true
  89154. });
  89155. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  89156. /**
  89157. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  89158. */
  89159. get: function () {
  89160. return this._idleRotationSpinupTime;
  89161. },
  89162. /**
  89163. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  89164. */
  89165. set: function (time) {
  89166. this._idleRotationSpinupTime = time;
  89167. },
  89168. enumerable: true,
  89169. configurable: true
  89170. });
  89171. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  89172. /**
  89173. * Gets a value indicating if the camera is currently rotating because of this behavior
  89174. */
  89175. get: function () {
  89176. return Math.abs(this._cameraRotationSpeed) > 0;
  89177. },
  89178. enumerable: true,
  89179. configurable: true
  89180. });
  89181. AutoRotationBehavior.prototype.init = function () {
  89182. // Do notihng
  89183. };
  89184. AutoRotationBehavior.prototype.attach = function (camera) {
  89185. var _this = this;
  89186. this._attachedCamera = camera;
  89187. var scene = this._attachedCamera.getScene();
  89188. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  89189. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  89190. _this._isPointerDown = true;
  89191. return;
  89192. }
  89193. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  89194. _this._isPointerDown = false;
  89195. }
  89196. });
  89197. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89198. var now = BABYLON.Tools.Now;
  89199. var dt = 0;
  89200. if (_this._lastFrameTime != null) {
  89201. dt = now - _this._lastFrameTime;
  89202. }
  89203. _this._lastFrameTime = now;
  89204. // Stop the animation if there is user interaction and the animation should stop for this interaction
  89205. _this._applyUserInteraction();
  89206. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  89207. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  89208. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  89209. // Step camera rotation by rotation speed
  89210. if (_this._attachedCamera) {
  89211. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  89212. }
  89213. });
  89214. };
  89215. AutoRotationBehavior.prototype.detach = function () {
  89216. if (!this._attachedCamera) {
  89217. return;
  89218. }
  89219. var scene = this._attachedCamera.getScene();
  89220. if (this._onPrePointerObservableObserver) {
  89221. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  89222. }
  89223. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89224. this._attachedCamera = null;
  89225. };
  89226. /**
  89227. * Returns true if user is scrolling.
  89228. * @return true if user is scrolling.
  89229. */
  89230. AutoRotationBehavior.prototype._userIsZooming = function () {
  89231. if (!this._attachedCamera) {
  89232. return false;
  89233. }
  89234. return this._attachedCamera.inertialRadiusOffset !== 0;
  89235. };
  89236. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  89237. if (!this._attachedCamera) {
  89238. return false;
  89239. }
  89240. var zoomHasHitLimit = false;
  89241. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  89242. zoomHasHitLimit = true;
  89243. }
  89244. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  89245. this._lastFrameRadius = this._attachedCamera.radius;
  89246. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  89247. };
  89248. /**
  89249. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  89250. */
  89251. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  89252. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  89253. this._lastInteractionTime = BABYLON.Tools.Now;
  89254. }
  89255. };
  89256. // Tools
  89257. AutoRotationBehavior.prototype._userIsMoving = function () {
  89258. if (!this._attachedCamera) {
  89259. return false;
  89260. }
  89261. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  89262. this._attachedCamera.inertialBetaOffset !== 0 ||
  89263. this._attachedCamera.inertialRadiusOffset !== 0 ||
  89264. this._attachedCamera.inertialPanningX !== 0 ||
  89265. this._attachedCamera.inertialPanningY !== 0 ||
  89266. this._isPointerDown;
  89267. };
  89268. return AutoRotationBehavior;
  89269. }());
  89270. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  89271. })(BABYLON || (BABYLON = {}));
  89272. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  89273. var BABYLON;
  89274. (function (BABYLON) {
  89275. var NullEngineOptions = /** @class */ (function () {
  89276. function NullEngineOptions() {
  89277. this.renderWidth = 512;
  89278. this.renderHeight = 256;
  89279. this.textureSize = 512;
  89280. this.deterministicLockstep = false;
  89281. this.lockstepMaxSteps = 4;
  89282. }
  89283. return NullEngineOptions;
  89284. }());
  89285. BABYLON.NullEngineOptions = NullEngineOptions;
  89286. /**
  89287. * The null engine class provides support for headless version of babylon.js.
  89288. * This can be used in server side scenario or for testing purposes
  89289. */
  89290. var NullEngine = /** @class */ (function (_super) {
  89291. __extends(NullEngine, _super);
  89292. function NullEngine(options) {
  89293. if (options === void 0) { options = new NullEngineOptions(); }
  89294. var _this = _super.call(this, null) || this;
  89295. if (options.deterministicLockstep === undefined) {
  89296. options.deterministicLockstep = false;
  89297. }
  89298. if (options.lockstepMaxSteps === undefined) {
  89299. options.lockstepMaxSteps = 4;
  89300. }
  89301. _this._options = options;
  89302. // Init caps
  89303. // We consider we are on a webgl1 capable device
  89304. _this._caps = new BABYLON.EngineCapabilities();
  89305. _this._caps.maxTexturesImageUnits = 16;
  89306. _this._caps.maxVertexTextureImageUnits = 16;
  89307. _this._caps.maxTextureSize = 512;
  89308. _this._caps.maxCubemapTextureSize = 512;
  89309. _this._caps.maxRenderTextureSize = 512;
  89310. _this._caps.maxVertexAttribs = 16;
  89311. _this._caps.maxVaryingVectors = 16;
  89312. _this._caps.maxFragmentUniformVectors = 16;
  89313. _this._caps.maxVertexUniformVectors = 16;
  89314. // Extensions
  89315. _this._caps.standardDerivatives = false;
  89316. _this._caps.astc = null;
  89317. _this._caps.s3tc = null;
  89318. _this._caps.pvrtc = null;
  89319. _this._caps.etc1 = null;
  89320. _this._caps.etc2 = null;
  89321. _this._caps.textureAnisotropicFilterExtension = null;
  89322. _this._caps.maxAnisotropy = 0;
  89323. _this._caps.uintIndices = false;
  89324. _this._caps.fragmentDepthSupported = false;
  89325. _this._caps.highPrecisionShaderSupported = true;
  89326. _this._caps.colorBufferFloat = false;
  89327. _this._caps.textureFloat = false;
  89328. _this._caps.textureFloatLinearFiltering = false;
  89329. _this._caps.textureFloatRender = false;
  89330. _this._caps.textureHalfFloat = false;
  89331. _this._caps.textureHalfFloatLinearFiltering = false;
  89332. _this._caps.textureHalfFloatRender = false;
  89333. _this._caps.textureLOD = false;
  89334. _this._caps.drawBuffersExtension = false;
  89335. _this._caps.depthTextureExtension = false;
  89336. _this._caps.vertexArrayObject = false;
  89337. _this._caps.instancedArrays = false;
  89338. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  89339. // Wrappers
  89340. if (typeof URL === "undefined") {
  89341. URL = {
  89342. createObjectURL: function () { },
  89343. revokeObjectURL: function () { }
  89344. };
  89345. }
  89346. if (typeof Blob === "undefined") {
  89347. Blob = function () { };
  89348. }
  89349. return _this;
  89350. }
  89351. NullEngine.prototype.isDeterministicLockStep = function () {
  89352. return this._options.deterministicLockstep;
  89353. };
  89354. NullEngine.prototype.getLockstepMaxSteps = function () {
  89355. return this._options.lockstepMaxSteps;
  89356. };
  89357. NullEngine.prototype.getHardwareScalingLevel = function () {
  89358. return 1.0;
  89359. };
  89360. NullEngine.prototype.createVertexBuffer = function (vertices) {
  89361. return {
  89362. capacity: 0,
  89363. references: 1,
  89364. is32Bits: false
  89365. };
  89366. };
  89367. NullEngine.prototype.createIndexBuffer = function (indices) {
  89368. return {
  89369. capacity: 0,
  89370. references: 1,
  89371. is32Bits: false
  89372. };
  89373. };
  89374. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  89375. if (stencil === void 0) { stencil = false; }
  89376. };
  89377. NullEngine.prototype.getRenderWidth = function (useScreen) {
  89378. if (useScreen === void 0) { useScreen = false; }
  89379. if (!useScreen && this._currentRenderTarget) {
  89380. return this._currentRenderTarget.width;
  89381. }
  89382. return this._options.renderWidth;
  89383. };
  89384. NullEngine.prototype.getRenderHeight = function (useScreen) {
  89385. if (useScreen === void 0) { useScreen = false; }
  89386. if (!useScreen && this._currentRenderTarget) {
  89387. return this._currentRenderTarget.height;
  89388. }
  89389. return this._options.renderHeight;
  89390. };
  89391. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  89392. this._cachedViewport = viewport;
  89393. };
  89394. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  89395. return {
  89396. transformFeedback: null,
  89397. __SPECTOR_rebuildProgram: null
  89398. };
  89399. };
  89400. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  89401. return [];
  89402. };
  89403. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  89404. return [];
  89405. };
  89406. NullEngine.prototype.bindSamplers = function (effect) {
  89407. this._currentEffect = null;
  89408. };
  89409. NullEngine.prototype.enableEffect = function (effect) {
  89410. this._currentEffect = effect;
  89411. if (effect.onBind) {
  89412. effect.onBind(effect);
  89413. }
  89414. effect.onBindObservable.notifyObservers(effect);
  89415. };
  89416. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  89417. if (zOffset === void 0) { zOffset = 0; }
  89418. if (reverseSide === void 0) { reverseSide = false; }
  89419. };
  89420. NullEngine.prototype.setIntArray = function (uniform, array) {
  89421. };
  89422. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  89423. };
  89424. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  89425. };
  89426. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  89427. };
  89428. NullEngine.prototype.setFloatArray = function (uniform, array) {
  89429. };
  89430. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  89431. };
  89432. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  89433. };
  89434. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  89435. };
  89436. NullEngine.prototype.setArray = function (uniform, array) {
  89437. };
  89438. NullEngine.prototype.setArray2 = function (uniform, array) {
  89439. };
  89440. NullEngine.prototype.setArray3 = function (uniform, array) {
  89441. };
  89442. NullEngine.prototype.setArray4 = function (uniform, array) {
  89443. };
  89444. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  89445. };
  89446. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  89447. };
  89448. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  89449. };
  89450. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  89451. };
  89452. NullEngine.prototype.setFloat = function (uniform, value) {
  89453. };
  89454. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  89455. };
  89456. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  89457. };
  89458. NullEngine.prototype.setBool = function (uniform, bool) {
  89459. };
  89460. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  89461. };
  89462. NullEngine.prototype.setColor3 = function (uniform, color3) {
  89463. };
  89464. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  89465. };
  89466. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  89467. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  89468. if (this._alphaMode === mode) {
  89469. return;
  89470. }
  89471. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  89472. if (!noDepthWriteChange) {
  89473. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  89474. }
  89475. this._alphaMode = mode;
  89476. };
  89477. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  89478. };
  89479. NullEngine.prototype.wipeCaches = function (bruteForce) {
  89480. if (this.preventCacheWipeBetweenFrames) {
  89481. return;
  89482. }
  89483. this.resetTextureCache();
  89484. this._currentEffect = null;
  89485. if (bruteForce) {
  89486. this._currentProgram = null;
  89487. this._stencilState.reset();
  89488. this._depthCullingState.reset();
  89489. this._alphaState.reset();
  89490. }
  89491. this._cachedVertexBuffers = null;
  89492. this._cachedIndexBuffer = null;
  89493. this._cachedEffectForVertexBuffers = null;
  89494. };
  89495. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  89496. };
  89497. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  89498. };
  89499. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  89500. };
  89501. NullEngine.prototype._createTexture = function () {
  89502. return {};
  89503. };
  89504. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  89505. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  89506. if (onLoad === void 0) { onLoad = null; }
  89507. if (onError === void 0) { onError = null; }
  89508. if (buffer === void 0) { buffer = null; }
  89509. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  89510. var url = String(urlArg);
  89511. texture.url = url;
  89512. texture.generateMipMaps = !noMipmap;
  89513. texture.samplingMode = samplingMode;
  89514. texture.invertY = invertY;
  89515. texture.baseWidth = this._options.textureSize;
  89516. texture.baseHeight = this._options.textureSize;
  89517. texture.width = this._options.textureSize;
  89518. texture.height = this._options.textureSize;
  89519. if (format) {
  89520. texture.format = format;
  89521. }
  89522. texture.isReady = true;
  89523. if (onLoad) {
  89524. onLoad();
  89525. }
  89526. return texture;
  89527. };
  89528. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  89529. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  89530. if (options !== undefined && typeof options === "object") {
  89531. fullOptions.generateMipMaps = options.generateMipMaps;
  89532. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  89533. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  89534. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  89535. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  89536. }
  89537. else {
  89538. fullOptions.generateMipMaps = options;
  89539. fullOptions.generateDepthBuffer = true;
  89540. fullOptions.generateStencilBuffer = false;
  89541. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89542. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  89543. }
  89544. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  89545. var width = size.width || size;
  89546. var height = size.height || size;
  89547. texture._depthStencilBuffer = {};
  89548. texture._framebuffer = {};
  89549. texture.baseWidth = width;
  89550. texture.baseHeight = height;
  89551. texture.width = width;
  89552. texture.height = height;
  89553. texture.isReady = true;
  89554. texture.samples = 1;
  89555. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  89556. texture.samplingMode = fullOptions.samplingMode;
  89557. texture.type = fullOptions.type;
  89558. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  89559. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  89560. return texture;
  89561. };
  89562. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  89563. texture.samplingMode = samplingMode;
  89564. };
  89565. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  89566. if (this._currentRenderTarget) {
  89567. this.unBindFramebuffer(this._currentRenderTarget);
  89568. }
  89569. this._currentRenderTarget = texture;
  89570. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  89571. if (this._cachedViewport && !forceFullscreenViewport) {
  89572. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  89573. }
  89574. };
  89575. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  89576. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  89577. this._currentRenderTarget = null;
  89578. if (onBeforeUnbind) {
  89579. if (texture._MSAAFramebuffer) {
  89580. this._currentFramebuffer = texture._framebuffer;
  89581. }
  89582. onBeforeUnbind();
  89583. }
  89584. this._currentFramebuffer = null;
  89585. };
  89586. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  89587. var vbo = {
  89588. capacity: 1,
  89589. references: 1,
  89590. is32Bits: false
  89591. };
  89592. return vbo;
  89593. };
  89594. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  89595. if (offset === void 0) { offset = 0; }
  89596. };
  89597. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  89598. };
  89599. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  89600. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  89601. this._boundTexturesCache[this._activeChannel] = texture;
  89602. }
  89603. };
  89604. NullEngine.prototype._bindTexture = function (channel, texture) {
  89605. if (channel < 0) {
  89606. return;
  89607. }
  89608. this._bindTextureDirectly(0, texture);
  89609. };
  89610. NullEngine.prototype._releaseBuffer = function (buffer) {
  89611. buffer.references--;
  89612. if (buffer.references === 0) {
  89613. return true;
  89614. }
  89615. return false;
  89616. };
  89617. return NullEngine;
  89618. }(BABYLON.Engine));
  89619. BABYLON.NullEngine = NullEngine;
  89620. })(BABYLON || (BABYLON = {}));
  89621. //# sourceMappingURL=babylon.nullEngine.js.map
  89622. var BABYLON;
  89623. (function (BABYLON) {
  89624. /**
  89625. * This class can be used to get instrumentation data from a Babylon engine
  89626. */
  89627. var EngineInstrumentation = /** @class */ (function () {
  89628. function EngineInstrumentation(engine) {
  89629. this.engine = engine;
  89630. this._captureGPUFrameTime = false;
  89631. this._gpuFrameTime = new BABYLON.PerfCounter();
  89632. this._captureShaderCompilationTime = false;
  89633. this._shaderCompilationTime = new BABYLON.PerfCounter();
  89634. // Observers
  89635. this._onBeginFrameObserver = null;
  89636. this._onEndFrameObserver = null;
  89637. this._onBeforeShaderCompilationObserver = null;
  89638. this._onAfterShaderCompilationObserver = null;
  89639. }
  89640. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  89641. // Properties
  89642. /**
  89643. * Gets the perf counter used for GPU frame time
  89644. */
  89645. get: function () {
  89646. return this._gpuFrameTime;
  89647. },
  89648. enumerable: true,
  89649. configurable: true
  89650. });
  89651. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  89652. /**
  89653. * Gets the GPU frame time capture status
  89654. */
  89655. get: function () {
  89656. return this._captureGPUFrameTime;
  89657. },
  89658. /**
  89659. * Enable or disable the GPU frame time capture
  89660. */
  89661. set: function (value) {
  89662. var _this = this;
  89663. if (value === this._captureGPUFrameTime) {
  89664. return;
  89665. }
  89666. this._captureGPUFrameTime = value;
  89667. if (value) {
  89668. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  89669. if (!_this._gpuFrameTimeToken) {
  89670. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  89671. }
  89672. });
  89673. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  89674. if (!_this._gpuFrameTimeToken) {
  89675. return;
  89676. }
  89677. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  89678. if (time > -1) {
  89679. _this._gpuFrameTimeToken = null;
  89680. _this._gpuFrameTime.fetchNewFrame();
  89681. _this._gpuFrameTime.addCount(time, true);
  89682. }
  89683. });
  89684. }
  89685. else {
  89686. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  89687. this._onBeginFrameObserver = null;
  89688. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  89689. this._onEndFrameObserver = null;
  89690. }
  89691. },
  89692. enumerable: true,
  89693. configurable: true
  89694. });
  89695. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  89696. /**
  89697. * Gets the perf counter used for shader compilation time
  89698. */
  89699. get: function () {
  89700. return this._shaderCompilationTime;
  89701. },
  89702. enumerable: true,
  89703. configurable: true
  89704. });
  89705. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  89706. /**
  89707. * Gets the shader compilation time capture status
  89708. */
  89709. get: function () {
  89710. return this._captureShaderCompilationTime;
  89711. },
  89712. /**
  89713. * Enable or disable the shader compilation time capture
  89714. */
  89715. set: function (value) {
  89716. var _this = this;
  89717. if (value === this._captureShaderCompilationTime) {
  89718. return;
  89719. }
  89720. this._captureShaderCompilationTime = value;
  89721. if (value) {
  89722. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  89723. _this._shaderCompilationTime.fetchNewFrame();
  89724. _this._shaderCompilationTime.beginMonitoring();
  89725. });
  89726. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  89727. _this._shaderCompilationTime.endMonitoring();
  89728. });
  89729. }
  89730. else {
  89731. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  89732. this._onBeforeShaderCompilationObserver = null;
  89733. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  89734. this._onAfterShaderCompilationObserver = null;
  89735. }
  89736. },
  89737. enumerable: true,
  89738. configurable: true
  89739. });
  89740. EngineInstrumentation.prototype.dispose = function () {
  89741. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  89742. this._onBeginFrameObserver = null;
  89743. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  89744. this._onEndFrameObserver = null;
  89745. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  89746. this._onBeforeShaderCompilationObserver = null;
  89747. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  89748. this._onAfterShaderCompilationObserver = null;
  89749. this.engine = null;
  89750. };
  89751. return EngineInstrumentation;
  89752. }());
  89753. BABYLON.EngineInstrumentation = EngineInstrumentation;
  89754. })(BABYLON || (BABYLON = {}));
  89755. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  89756. var BABYLON;
  89757. (function (BABYLON) {
  89758. /**
  89759. * This class can be used to get instrumentation data from a Babylon engine
  89760. */
  89761. var SceneInstrumentation = /** @class */ (function () {
  89762. function SceneInstrumentation(scene) {
  89763. var _this = this;
  89764. this.scene = scene;
  89765. this._captureActiveMeshesEvaluationTime = false;
  89766. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  89767. this._captureRenderTargetsRenderTime = false;
  89768. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  89769. this._captureFrameTime = false;
  89770. this._frameTime = new BABYLON.PerfCounter();
  89771. this._captureRenderTime = false;
  89772. this._renderTime = new BABYLON.PerfCounter();
  89773. this._captureInterFrameTime = false;
  89774. this._interFrameTime = new BABYLON.PerfCounter();
  89775. this._captureParticlesRenderTime = false;
  89776. this._particlesRenderTime = new BABYLON.PerfCounter();
  89777. this._captureSpritesRenderTime = false;
  89778. this._spritesRenderTime = new BABYLON.PerfCounter();
  89779. this._capturePhysicsTime = false;
  89780. this._physicsTime = new BABYLON.PerfCounter();
  89781. this._captureAnimationsTime = false;
  89782. this._animationsTime = new BABYLON.PerfCounter();
  89783. // Observers
  89784. this._onBeforeActiveMeshesEvaluationObserver = null;
  89785. this._onAfterActiveMeshesEvaluationObserver = null;
  89786. this._onBeforeRenderTargetsRenderObserver = null;
  89787. this._onAfterRenderTargetsRenderObserver = null;
  89788. this._onAfterRenderObserver = null;
  89789. this._onBeforeDrawPhaseObserver = null;
  89790. this._onAfterDrawPhaseObserver = null;
  89791. this._onBeforeAnimationsObserver = null;
  89792. this._onBeforeParticlesRenderingObserver = null;
  89793. this._onAfterParticlesRenderingObserver = null;
  89794. this._onBeforeSpritesRenderingObserver = null;
  89795. this._onAfterSpritesRenderingObserver = null;
  89796. this._onBeforePhysicsObserver = null;
  89797. this._onAfterPhysicsObserver = null;
  89798. this._onAfterAnimationsObserver = null;
  89799. // Before render
  89800. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  89801. if (_this._captureActiveMeshesEvaluationTime) {
  89802. _this._activeMeshesEvaluationTime.fetchNewFrame();
  89803. }
  89804. if (_this._captureRenderTargetsRenderTime) {
  89805. _this._renderTargetsRenderTime.fetchNewFrame();
  89806. }
  89807. if (_this._captureFrameTime) {
  89808. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  89809. _this._frameTime.beginMonitoring();
  89810. }
  89811. if (_this._captureInterFrameTime) {
  89812. _this._interFrameTime.endMonitoring();
  89813. }
  89814. if (_this._captureParticlesRenderTime) {
  89815. _this._particlesRenderTime.fetchNewFrame();
  89816. }
  89817. if (_this._captureSpritesRenderTime) {
  89818. _this._spritesRenderTime.fetchNewFrame();
  89819. }
  89820. if (_this._captureAnimationsTime) {
  89821. _this._animationsTime.beginMonitoring();
  89822. }
  89823. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  89824. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  89825. });
  89826. // After render
  89827. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  89828. if (_this._captureFrameTime) {
  89829. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  89830. _this._frameTime.endMonitoring();
  89831. }
  89832. if (_this._captureRenderTime) {
  89833. _this._renderTime.endMonitoring(false);
  89834. }
  89835. if (_this._captureInterFrameTime) {
  89836. _this._interFrameTime.beginMonitoring();
  89837. }
  89838. });
  89839. }
  89840. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  89841. // Properties
  89842. /**
  89843. * Gets the perf counter used for active meshes evaluation time
  89844. */
  89845. get: function () {
  89846. return this._activeMeshesEvaluationTime;
  89847. },
  89848. enumerable: true,
  89849. configurable: true
  89850. });
  89851. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  89852. /**
  89853. * Gets the active meshes evaluation time capture status
  89854. */
  89855. get: function () {
  89856. return this._captureActiveMeshesEvaluationTime;
  89857. },
  89858. /**
  89859. * Enable or disable the active meshes evaluation time capture
  89860. */
  89861. set: function (value) {
  89862. var _this = this;
  89863. if (value === this._captureActiveMeshesEvaluationTime) {
  89864. return;
  89865. }
  89866. this._captureActiveMeshesEvaluationTime = value;
  89867. if (value) {
  89868. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  89869. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  89870. _this._activeMeshesEvaluationTime.beginMonitoring();
  89871. });
  89872. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  89873. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  89874. _this._activeMeshesEvaluationTime.endMonitoring();
  89875. });
  89876. }
  89877. else {
  89878. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  89879. this._onBeforeActiveMeshesEvaluationObserver = null;
  89880. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  89881. this._onAfterActiveMeshesEvaluationObserver = null;
  89882. }
  89883. },
  89884. enumerable: true,
  89885. configurable: true
  89886. });
  89887. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  89888. /**
  89889. * Gets the perf counter used for render targets render time
  89890. */
  89891. get: function () {
  89892. return this._renderTargetsRenderTime;
  89893. },
  89894. enumerable: true,
  89895. configurable: true
  89896. });
  89897. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  89898. /**
  89899. * Gets the render targets render time capture status
  89900. */
  89901. get: function () {
  89902. return this._captureRenderTargetsRenderTime;
  89903. },
  89904. /**
  89905. * Enable or disable the render targets render time capture
  89906. */
  89907. set: function (value) {
  89908. var _this = this;
  89909. if (value === this._captureRenderTargetsRenderTime) {
  89910. return;
  89911. }
  89912. this._captureRenderTargetsRenderTime = value;
  89913. if (value) {
  89914. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  89915. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  89916. _this._renderTargetsRenderTime.beginMonitoring();
  89917. });
  89918. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  89919. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  89920. _this._renderTargetsRenderTime.endMonitoring(false);
  89921. });
  89922. }
  89923. else {
  89924. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  89925. this._onBeforeRenderTargetsRenderObserver = null;
  89926. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  89927. this._onAfterRenderTargetsRenderObserver = null;
  89928. }
  89929. },
  89930. enumerable: true,
  89931. configurable: true
  89932. });
  89933. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  89934. /**
  89935. * Gets the perf counter used for particles render time
  89936. */
  89937. get: function () {
  89938. return this._particlesRenderTime;
  89939. },
  89940. enumerable: true,
  89941. configurable: true
  89942. });
  89943. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  89944. /**
  89945. * Gets the particles render time capture status
  89946. */
  89947. get: function () {
  89948. return this._captureParticlesRenderTime;
  89949. },
  89950. /**
  89951. * Enable or disable the particles render time capture
  89952. */
  89953. set: function (value) {
  89954. var _this = this;
  89955. if (value === this._captureParticlesRenderTime) {
  89956. return;
  89957. }
  89958. this._captureParticlesRenderTime = value;
  89959. if (value) {
  89960. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  89961. BABYLON.Tools.StartPerformanceCounter("Particles");
  89962. _this._particlesRenderTime.beginMonitoring();
  89963. });
  89964. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  89965. BABYLON.Tools.EndPerformanceCounter("Particles");
  89966. _this._particlesRenderTime.endMonitoring(false);
  89967. });
  89968. }
  89969. else {
  89970. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  89971. this._onBeforeParticlesRenderingObserver = null;
  89972. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  89973. this._onAfterParticlesRenderingObserver = null;
  89974. }
  89975. },
  89976. enumerable: true,
  89977. configurable: true
  89978. });
  89979. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  89980. /**
  89981. * Gets the perf counter used for sprites render time
  89982. */
  89983. get: function () {
  89984. return this._spritesRenderTime;
  89985. },
  89986. enumerable: true,
  89987. configurable: true
  89988. });
  89989. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  89990. /**
  89991. * Gets the sprites render time capture status
  89992. */
  89993. get: function () {
  89994. return this._captureSpritesRenderTime;
  89995. },
  89996. /**
  89997. * Enable or disable the sprites render time capture
  89998. */
  89999. set: function (value) {
  90000. var _this = this;
  90001. if (value === this._captureSpritesRenderTime) {
  90002. return;
  90003. }
  90004. this._captureSpritesRenderTime = value;
  90005. if (value) {
  90006. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  90007. BABYLON.Tools.StartPerformanceCounter("Sprites");
  90008. _this._spritesRenderTime.beginMonitoring();
  90009. });
  90010. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  90011. BABYLON.Tools.EndPerformanceCounter("Sprites");
  90012. _this._spritesRenderTime.endMonitoring(false);
  90013. });
  90014. }
  90015. else {
  90016. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  90017. this._onBeforeSpritesRenderingObserver = null;
  90018. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  90019. this._onAfterSpritesRenderingObserver = null;
  90020. }
  90021. },
  90022. enumerable: true,
  90023. configurable: true
  90024. });
  90025. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  90026. /**
  90027. * Gets the perf counter used for physics time
  90028. */
  90029. get: function () {
  90030. return this._physicsTime;
  90031. },
  90032. enumerable: true,
  90033. configurable: true
  90034. });
  90035. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  90036. /**
  90037. * Gets the physics time capture status
  90038. */
  90039. get: function () {
  90040. return this._capturePhysicsTime;
  90041. },
  90042. /**
  90043. * Enable or disable the physics time capture
  90044. */
  90045. set: function (value) {
  90046. var _this = this;
  90047. if (value === this._capturePhysicsTime) {
  90048. return;
  90049. }
  90050. this._capturePhysicsTime = value;
  90051. if (value) {
  90052. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  90053. BABYLON.Tools.StartPerformanceCounter("Physics");
  90054. _this._physicsTime.beginMonitoring();
  90055. });
  90056. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  90057. BABYLON.Tools.EndPerformanceCounter("Physics");
  90058. _this._physicsTime.endMonitoring();
  90059. });
  90060. }
  90061. else {
  90062. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  90063. this._onBeforePhysicsObserver = null;
  90064. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  90065. this._onAfterPhysicsObserver = null;
  90066. }
  90067. },
  90068. enumerable: true,
  90069. configurable: true
  90070. });
  90071. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  90072. /**
  90073. * Gets the perf counter used for animations time
  90074. */
  90075. get: function () {
  90076. return this._animationsTime;
  90077. },
  90078. enumerable: true,
  90079. configurable: true
  90080. });
  90081. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  90082. /**
  90083. * Gets the animations time capture status
  90084. */
  90085. get: function () {
  90086. return this._captureAnimationsTime;
  90087. },
  90088. /**
  90089. * Enable or disable the animations time capture
  90090. */
  90091. set: function (value) {
  90092. var _this = this;
  90093. if (value === this._captureAnimationsTime) {
  90094. return;
  90095. }
  90096. this._captureAnimationsTime = value;
  90097. if (value) {
  90098. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  90099. _this._animationsTime.endMonitoring();
  90100. });
  90101. }
  90102. else {
  90103. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  90104. this._onAfterAnimationsObserver = null;
  90105. }
  90106. },
  90107. enumerable: true,
  90108. configurable: true
  90109. });
  90110. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  90111. /**
  90112. * Gets the perf counter used for frame time capture
  90113. */
  90114. get: function () {
  90115. return this._frameTime;
  90116. },
  90117. enumerable: true,
  90118. configurable: true
  90119. });
  90120. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  90121. /**
  90122. * Gets the frame time capture status
  90123. */
  90124. get: function () {
  90125. return this._captureFrameTime;
  90126. },
  90127. /**
  90128. * Enable or disable the frame time capture
  90129. */
  90130. set: function (value) {
  90131. this._captureFrameTime = value;
  90132. },
  90133. enumerable: true,
  90134. configurable: true
  90135. });
  90136. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  90137. /**
  90138. * Gets the perf counter used for inter-frames time capture
  90139. */
  90140. get: function () {
  90141. return this._interFrameTime;
  90142. },
  90143. enumerable: true,
  90144. configurable: true
  90145. });
  90146. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  90147. /**
  90148. * Gets the inter-frames time capture status
  90149. */
  90150. get: function () {
  90151. return this._captureInterFrameTime;
  90152. },
  90153. /**
  90154. * Enable or disable the inter-frames time capture
  90155. */
  90156. set: function (value) {
  90157. this._captureInterFrameTime = value;
  90158. },
  90159. enumerable: true,
  90160. configurable: true
  90161. });
  90162. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  90163. /**
  90164. * Gets the perf counter used for render time capture
  90165. */
  90166. get: function () {
  90167. return this._renderTime;
  90168. },
  90169. enumerable: true,
  90170. configurable: true
  90171. });
  90172. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  90173. /**
  90174. * Gets the render time capture status
  90175. */
  90176. get: function () {
  90177. return this._captureRenderTime;
  90178. },
  90179. /**
  90180. * Enable or disable the render time capture
  90181. */
  90182. set: function (value) {
  90183. var _this = this;
  90184. if (value === this._captureRenderTime) {
  90185. return;
  90186. }
  90187. this._captureRenderTime = value;
  90188. if (value) {
  90189. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  90190. _this._renderTime.beginMonitoring();
  90191. BABYLON.Tools.StartPerformanceCounter("Main render");
  90192. });
  90193. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  90194. _this._renderTime.endMonitoring(false);
  90195. BABYLON.Tools.EndPerformanceCounter("Main render");
  90196. });
  90197. }
  90198. else {
  90199. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  90200. this._onBeforeDrawPhaseObserver = null;
  90201. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  90202. this._onAfterDrawPhaseObserver = null;
  90203. }
  90204. },
  90205. enumerable: true,
  90206. configurable: true
  90207. });
  90208. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  90209. /**
  90210. * Gets the perf counter used for draw calls
  90211. */
  90212. get: function () {
  90213. return this.scene.getEngine()._drawCalls;
  90214. },
  90215. enumerable: true,
  90216. configurable: true
  90217. });
  90218. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  90219. /**
  90220. * Gets the perf counter used for texture collisions
  90221. */
  90222. get: function () {
  90223. return this.scene.getEngine()._textureCollisions;
  90224. },
  90225. enumerable: true,
  90226. configurable: true
  90227. });
  90228. SceneInstrumentation.prototype.dispose = function () {
  90229. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  90230. this._onAfterRenderObserver = null;
  90231. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  90232. this._onBeforeActiveMeshesEvaluationObserver = null;
  90233. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  90234. this._onAfterActiveMeshesEvaluationObserver = null;
  90235. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  90236. this._onBeforeRenderTargetsRenderObserver = null;
  90237. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  90238. this._onAfterRenderTargetsRenderObserver = null;
  90239. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  90240. this._onBeforeAnimationsObserver = null;
  90241. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  90242. this._onBeforeParticlesRenderingObserver = null;
  90243. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  90244. this._onAfterParticlesRenderingObserver = null;
  90245. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  90246. this._onBeforeSpritesRenderingObserver = null;
  90247. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  90248. this._onAfterSpritesRenderingObserver = null;
  90249. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  90250. this._onBeforeDrawPhaseObserver = null;
  90251. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  90252. this._onAfterDrawPhaseObserver = null;
  90253. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  90254. this._onBeforePhysicsObserver = null;
  90255. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  90256. this._onAfterPhysicsObserver = null;
  90257. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  90258. this._onAfterAnimationsObserver = null;
  90259. this.scene = null;
  90260. };
  90261. return SceneInstrumentation;
  90262. }());
  90263. BABYLON.SceneInstrumentation = SceneInstrumentation;
  90264. })(BABYLON || (BABYLON = {}));
  90265. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  90266. var BABYLON;
  90267. (function (BABYLON) {
  90268. var _TimeToken = /** @class */ (function () {
  90269. function _TimeToken() {
  90270. this._timeElapsedQueryEnded = false;
  90271. }
  90272. return _TimeToken;
  90273. }());
  90274. BABYLON._TimeToken = _TimeToken;
  90275. })(BABYLON || (BABYLON = {}));
  90276. //# sourceMappingURL=babylon.timeToken.js.map
  90277. var BABYLON;
  90278. (function (BABYLON) {
  90279. /**
  90280. * Background material defines definition.
  90281. * @ignore Mainly internal Use
  90282. */
  90283. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  90284. __extends(BackgroundMaterialDefines, _super);
  90285. /**
  90286. * Constructor of the defines.
  90287. */
  90288. function BackgroundMaterialDefines() {
  90289. var _this = _super.call(this) || this;
  90290. /**
  90291. * True if the diffuse texture is in use.
  90292. */
  90293. _this.DIFFUSE = false;
  90294. /**
  90295. * The direct UV channel to use.
  90296. */
  90297. _this.DIFFUSEDIRECTUV = 0;
  90298. /**
  90299. * True if the diffuse texture is in gamma space.
  90300. */
  90301. _this.GAMMADIFFUSE = false;
  90302. /**
  90303. * True if the diffuse texture has opacity in the alpha channel.
  90304. */
  90305. _this.DIFFUSEHASALPHA = false;
  90306. /**
  90307. * True if you want the material to fade to transparent at grazing angle.
  90308. */
  90309. _this.OPACITYFRESNEL = false;
  90310. /**
  90311. * True if an extra blur needs to be added in the reflection.
  90312. */
  90313. _this.REFLECTIONBLUR = false;
  90314. /**
  90315. * True if you want the material to fade to reflection at grazing angle.
  90316. */
  90317. _this.REFLECTIONFRESNEL = false;
  90318. /**
  90319. * True if you want the material to falloff as far as you move away from the scene center.
  90320. */
  90321. _this.REFLECTIONFALLOFF = false;
  90322. /**
  90323. * False if the current Webgl implementation does not support the texture lod extension.
  90324. */
  90325. _this.TEXTURELODSUPPORT = false;
  90326. /**
  90327. * True to ensure the data are premultiplied.
  90328. */
  90329. _this.PREMULTIPLYALPHA = false;
  90330. /**
  90331. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  90332. */
  90333. _this.USERGBCOLOR = false;
  90334. /**
  90335. * True to add noise in order to reduce the banding effect.
  90336. */
  90337. _this.NOISE = false;
  90338. /**
  90339. * is the reflection texture in BGR color scheme?
  90340. * Mainly used to solve a bug in ios10 video tag
  90341. */
  90342. _this.REFLECTIONBGR = false;
  90343. _this.IMAGEPROCESSING = false;
  90344. _this.VIGNETTE = false;
  90345. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  90346. _this.VIGNETTEBLENDMODEOPAQUE = false;
  90347. _this.TONEMAPPING = false;
  90348. _this.CONTRAST = false;
  90349. _this.COLORCURVES = false;
  90350. _this.COLORGRADING = false;
  90351. _this.COLORGRADING3D = false;
  90352. _this.SAMPLER3DGREENDEPTH = false;
  90353. _this.SAMPLER3DBGRMAP = false;
  90354. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  90355. _this.EXPOSURE = false;
  90356. _this.GRAIN = false;
  90357. // Reflection.
  90358. _this.REFLECTION = false;
  90359. _this.REFLECTIONMAP_3D = false;
  90360. _this.REFLECTIONMAP_SPHERICAL = false;
  90361. _this.REFLECTIONMAP_PLANAR = false;
  90362. _this.REFLECTIONMAP_CUBIC = false;
  90363. _this.REFLECTIONMAP_PROJECTION = false;
  90364. _this.REFLECTIONMAP_SKYBOX = false;
  90365. _this.REFLECTIONMAP_EXPLICIT = false;
  90366. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  90367. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  90368. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  90369. _this.INVERTCUBICMAP = false;
  90370. _this.REFLECTIONMAP_OPPOSITEZ = false;
  90371. _this.LODINREFLECTIONALPHA = false;
  90372. _this.GAMMAREFLECTION = false;
  90373. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  90374. // Default BJS.
  90375. _this.MAINUV1 = false;
  90376. _this.MAINUV2 = false;
  90377. _this.UV1 = false;
  90378. _this.UV2 = false;
  90379. _this.CLIPPLANE = false;
  90380. _this.POINTSIZE = false;
  90381. _this.FOG = false;
  90382. _this.NORMAL = false;
  90383. _this.NUM_BONE_INFLUENCERS = 0;
  90384. _this.BonesPerMesh = 0;
  90385. _this.INSTANCES = false;
  90386. _this.SHADOWFLOAT = false;
  90387. _this.rebuild();
  90388. return _this;
  90389. }
  90390. return BackgroundMaterialDefines;
  90391. }(BABYLON.MaterialDefines));
  90392. /**
  90393. * Background material used to create an efficient environement around your scene.
  90394. */
  90395. var BackgroundMaterial = /** @class */ (function (_super) {
  90396. __extends(BackgroundMaterial, _super);
  90397. /**
  90398. * Instantiates a Background Material in the given scene
  90399. * @param name The friendly name of the material
  90400. * @param scene The scene to add the material to
  90401. */
  90402. function BackgroundMaterial(name, scene) {
  90403. var _this = _super.call(this, name, scene) || this;
  90404. /**
  90405. * Key light Color (multiply against the R channel of the environement texture)
  90406. */
  90407. _this.primaryColor = BABYLON.Color3.White();
  90408. /**
  90409. * Key light Level (allowing HDR output of the background)
  90410. */
  90411. _this.primaryLevel = 1;
  90412. /**
  90413. * Secondary light Color (multiply against the G channel of the environement texture)
  90414. */
  90415. _this.secondaryColor = BABYLON.Color3.Gray();
  90416. /**
  90417. * Secondary light Level (allowing HDR output of the background)
  90418. */
  90419. _this.secondaryLevel = 1;
  90420. /**
  90421. * Tertiary light Color (multiply against the B channel of the environement texture)
  90422. */
  90423. _this.tertiaryColor = BABYLON.Color3.Black();
  90424. /**
  90425. * Tertiary light Level (allowing HDR output of the background)
  90426. */
  90427. _this.tertiaryLevel = 1;
  90428. /**
  90429. * Reflection Texture used in the material.
  90430. * Should be author in a specific way for the best result (refer to the documentation).
  90431. */
  90432. _this.reflectionTexture = null;
  90433. /**
  90434. * Reflection Texture level of blur.
  90435. *
  90436. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  90437. * texture twice.
  90438. */
  90439. _this.reflectionBlur = 0;
  90440. /**
  90441. * Diffuse Texture used in the material.
  90442. * Should be author in a specific way for the best result (refer to the documentation).
  90443. */
  90444. _this.diffuseTexture = null;
  90445. _this._shadowLights = null;
  90446. /**
  90447. * Specify the list of lights casting shadow on the material.
  90448. * All scene shadow lights will be included if null.
  90449. */
  90450. _this.shadowLights = null;
  90451. /**
  90452. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  90453. * soft lighting on the background.
  90454. */
  90455. _this.shadowBlurScale = 1;
  90456. /**
  90457. * Helps adjusting the shadow to a softer level if required.
  90458. * 0 means black shadows and 1 means no shadows.
  90459. */
  90460. _this.shadowLevel = 0;
  90461. /**
  90462. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  90463. * It is usually zero but might be interesting to modify according to your setup.
  90464. */
  90465. _this.sceneCenter = BABYLON.Vector3.Zero();
  90466. /**
  90467. * This helps specifying that the material is falling off to the sky box at grazing angle.
  90468. * This helps ensuring a nice transition when the camera goes under the ground.
  90469. */
  90470. _this.opacityFresnel = true;
  90471. /**
  90472. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  90473. * This helps adding a mirror texture on the ground.
  90474. */
  90475. _this.reflectionFresnel = false;
  90476. /**
  90477. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  90478. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  90479. */
  90480. _this.reflectionFalloffDistance = 0.0;
  90481. /**
  90482. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  90483. */
  90484. _this.reflectionAmount = 1.0;
  90485. /**
  90486. * This specifies the weight of the reflection at grazing angle.
  90487. */
  90488. _this.reflectionReflectance0 = 0.05;
  90489. /**
  90490. * This specifies the weight of the reflection at a perpendicular point of view.
  90491. */
  90492. _this.reflectionReflectance90 = 0.5;
  90493. /**
  90494. * Helps to directly use the maps channels instead of their level.
  90495. */
  90496. _this.useRGBColor = true;
  90497. /**
  90498. * This helps reducing the banding effect that could occur on the background.
  90499. */
  90500. _this.enableNoise = false;
  90501. _this._fovMultiplier = 1.0;
  90502. /**
  90503. * Enable the FOV adjustment feature controlled by fovMultiplier.
  90504. * @type {boolean}
  90505. */
  90506. _this.useEquirectangularFOV = false;
  90507. _this._maxSimultaneousLights = 4;
  90508. /**
  90509. * Number of Simultaneous lights allowed on the material.
  90510. */
  90511. _this.maxSimultaneousLights = 4;
  90512. /**
  90513. * Keep track of the image processing observer to allow dispose and replace.
  90514. */
  90515. _this._imageProcessingObserver = null;
  90516. /**
  90517. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  90518. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  90519. */
  90520. _this.switchToBGR = false;
  90521. // Temp values kept as cache in the material.
  90522. _this._renderTargets = new BABYLON.SmartArray(16);
  90523. _this._reflectionControls = BABYLON.Vector4.Zero();
  90524. // Setup the default processing configuration to the scene.
  90525. _this._attachImageProcessingConfiguration(null);
  90526. _this.getRenderTargetTextures = function () {
  90527. _this._renderTargets.reset();
  90528. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  90529. _this._renderTargets.push(_this._diffuseTexture);
  90530. }
  90531. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  90532. _this._renderTargets.push(_this._reflectionTexture);
  90533. }
  90534. return _this._renderTargets;
  90535. };
  90536. return _this;
  90537. }
  90538. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  90539. /**
  90540. * Sets the reflection reflectance fresnel values according to the default standard
  90541. * empirically know to work well :-)
  90542. */
  90543. set: function (value) {
  90544. var reflectionWeight = value;
  90545. if (reflectionWeight < 0.5) {
  90546. reflectionWeight = reflectionWeight * 2.0;
  90547. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  90548. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  90549. }
  90550. else {
  90551. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  90552. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  90553. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  90554. }
  90555. },
  90556. enumerable: true,
  90557. configurable: true
  90558. });
  90559. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  90560. /**
  90561. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  90562. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  90563. * Recommended to be keep at 1.0 except for special cases.
  90564. */
  90565. get: function () {
  90566. return this._fovMultiplier;
  90567. },
  90568. set: function (value) {
  90569. if (isNaN(value)) {
  90570. value = 1.0;
  90571. }
  90572. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  90573. },
  90574. enumerable: true,
  90575. configurable: true
  90576. });
  90577. /**
  90578. * Attaches a new image processing configuration to the PBR Material.
  90579. * @param configuration (if null the scene configuration will be use)
  90580. */
  90581. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  90582. var _this = this;
  90583. if (configuration === this._imageProcessingConfiguration) {
  90584. return;
  90585. }
  90586. // Detaches observer.
  90587. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  90588. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  90589. }
  90590. // Pick the scene configuration if needed.
  90591. if (!configuration) {
  90592. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  90593. }
  90594. else {
  90595. this._imageProcessingConfiguration = configuration;
  90596. }
  90597. // Attaches observer.
  90598. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  90599. _this._markAllSubMeshesAsImageProcessingDirty();
  90600. });
  90601. };
  90602. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  90603. /**
  90604. * Gets the image processing configuration used either in this material.
  90605. */
  90606. get: function () {
  90607. return this._imageProcessingConfiguration;
  90608. },
  90609. /**
  90610. * Sets the Default image processing configuration used either in the this material.
  90611. *
  90612. * If sets to null, the scene one is in use.
  90613. */
  90614. set: function (value) {
  90615. this._attachImageProcessingConfiguration(value);
  90616. // Ensure the effect will be rebuilt.
  90617. this._markAllSubMeshesAsTexturesDirty();
  90618. },
  90619. enumerable: true,
  90620. configurable: true
  90621. });
  90622. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  90623. /**
  90624. * Gets wether the color curves effect is enabled.
  90625. */
  90626. get: function () {
  90627. return this.imageProcessingConfiguration.colorCurvesEnabled;
  90628. },
  90629. /**
  90630. * Sets wether the color curves effect is enabled.
  90631. */
  90632. set: function (value) {
  90633. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  90634. },
  90635. enumerable: true,
  90636. configurable: true
  90637. });
  90638. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  90639. /**
  90640. * Gets wether the color grading effect is enabled.
  90641. */
  90642. get: function () {
  90643. return this.imageProcessingConfiguration.colorGradingEnabled;
  90644. },
  90645. /**
  90646. * Gets wether the color grading effect is enabled.
  90647. */
  90648. set: function (value) {
  90649. this.imageProcessingConfiguration.colorGradingEnabled = value;
  90650. },
  90651. enumerable: true,
  90652. configurable: true
  90653. });
  90654. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  90655. /**
  90656. * Gets wether tonemapping is enabled or not.
  90657. */
  90658. get: function () {
  90659. return this._imageProcessingConfiguration.toneMappingEnabled;
  90660. },
  90661. /**
  90662. * Sets wether tonemapping is enabled or not
  90663. */
  90664. set: function (value) {
  90665. this._imageProcessingConfiguration.toneMappingEnabled = value;
  90666. },
  90667. enumerable: true,
  90668. configurable: true
  90669. });
  90670. ;
  90671. ;
  90672. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  90673. /**
  90674. * The camera exposure used on this material.
  90675. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  90676. * This corresponds to a photographic exposure.
  90677. */
  90678. get: function () {
  90679. return this._imageProcessingConfiguration.exposure;
  90680. },
  90681. /**
  90682. * The camera exposure used on this material.
  90683. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  90684. * This corresponds to a photographic exposure.
  90685. */
  90686. set: function (value) {
  90687. this._imageProcessingConfiguration.exposure = value;
  90688. },
  90689. enumerable: true,
  90690. configurable: true
  90691. });
  90692. ;
  90693. ;
  90694. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  90695. /**
  90696. * Gets The camera contrast used on this material.
  90697. */
  90698. get: function () {
  90699. return this._imageProcessingConfiguration.contrast;
  90700. },
  90701. /**
  90702. * Sets The camera contrast used on this material.
  90703. */
  90704. set: function (value) {
  90705. this._imageProcessingConfiguration.contrast = value;
  90706. },
  90707. enumerable: true,
  90708. configurable: true
  90709. });
  90710. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  90711. /**
  90712. * Gets the Color Grading 2D Lookup Texture.
  90713. */
  90714. get: function () {
  90715. return this._imageProcessingConfiguration.colorGradingTexture;
  90716. },
  90717. /**
  90718. * Sets the Color Grading 2D Lookup Texture.
  90719. */
  90720. set: function (value) {
  90721. this.imageProcessingConfiguration.colorGradingTexture = value;
  90722. },
  90723. enumerable: true,
  90724. configurable: true
  90725. });
  90726. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  90727. /**
  90728. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  90729. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  90730. * 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;
  90731. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  90732. */
  90733. get: function () {
  90734. return this.imageProcessingConfiguration.colorCurves;
  90735. },
  90736. /**
  90737. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  90738. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  90739. * 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;
  90740. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  90741. */
  90742. set: function (value) {
  90743. this.imageProcessingConfiguration.colorCurves = value;
  90744. },
  90745. enumerable: true,
  90746. configurable: true
  90747. });
  90748. /**
  90749. * The entire material has been created in order to prevent overdraw.
  90750. * @returns false
  90751. */
  90752. BackgroundMaterial.prototype.needAlphaTesting = function () {
  90753. return true;
  90754. };
  90755. /**
  90756. * The entire material has been created in order to prevent overdraw.
  90757. * @returns true if blending is enable
  90758. */
  90759. BackgroundMaterial.prototype.needAlphaBlending = function () {
  90760. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  90761. };
  90762. /**
  90763. * Checks wether the material is ready to be rendered for a given mesh.
  90764. * @param mesh The mesh to render
  90765. * @param subMesh The submesh to check against
  90766. * @param useInstances Specify wether or not the material is used with instances
  90767. * @returns true if all the dependencies are ready (Textures, Effects...)
  90768. */
  90769. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  90770. var _this = this;
  90771. if (useInstances === void 0) { useInstances = false; }
  90772. if (subMesh.effect && this.isFrozen) {
  90773. if (this._wasPreviouslyReady) {
  90774. return true;
  90775. }
  90776. }
  90777. if (!subMesh._materialDefines) {
  90778. subMesh._materialDefines = new BackgroundMaterialDefines();
  90779. }
  90780. var scene = this.getScene();
  90781. var defines = subMesh._materialDefines;
  90782. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  90783. if (defines._renderId === scene.getRenderId()) {
  90784. return true;
  90785. }
  90786. }
  90787. var engine = scene.getEngine();
  90788. // Lights
  90789. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  90790. defines._needNormals = true;
  90791. // Textures
  90792. if (defines._areTexturesDirty) {
  90793. defines._needUVs = false;
  90794. if (scene.texturesEnabled) {
  90795. if (scene.getEngine().getCaps().textureLOD) {
  90796. defines.TEXTURELODSUPPORT = true;
  90797. }
  90798. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  90799. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  90800. return false;
  90801. }
  90802. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  90803. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  90804. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  90805. defines.OPACITYFRESNEL = this._opacityFresnel;
  90806. }
  90807. else {
  90808. defines.DIFFUSE = false;
  90809. defines.DIFFUSEHASALPHA = false;
  90810. defines.GAMMADIFFUSE = false;
  90811. defines.OPACITYFRESNEL = false;
  90812. }
  90813. var reflectionTexture = this._reflectionTexture;
  90814. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  90815. if (!reflectionTexture.isReadyOrNotBlocking()) {
  90816. return false;
  90817. }
  90818. defines.REFLECTION = true;
  90819. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  90820. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  90821. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  90822. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  90823. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  90824. defines.REFLECTIONBGR = this.switchToBGR;
  90825. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  90826. defines.INVERTCUBICMAP = true;
  90827. }
  90828. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  90829. switch (reflectionTexture.coordinatesMode) {
  90830. case BABYLON.Texture.CUBIC_MODE:
  90831. case BABYLON.Texture.INVCUBIC_MODE:
  90832. defines.REFLECTIONMAP_CUBIC = true;
  90833. break;
  90834. case BABYLON.Texture.EXPLICIT_MODE:
  90835. defines.REFLECTIONMAP_EXPLICIT = true;
  90836. break;
  90837. case BABYLON.Texture.PLANAR_MODE:
  90838. defines.REFLECTIONMAP_PLANAR = true;
  90839. break;
  90840. case BABYLON.Texture.PROJECTION_MODE:
  90841. defines.REFLECTIONMAP_PROJECTION = true;
  90842. break;
  90843. case BABYLON.Texture.SKYBOX_MODE:
  90844. defines.REFLECTIONMAP_SKYBOX = true;
  90845. break;
  90846. case BABYLON.Texture.SPHERICAL_MODE:
  90847. defines.REFLECTIONMAP_SPHERICAL = true;
  90848. break;
  90849. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  90850. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  90851. break;
  90852. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  90853. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  90854. break;
  90855. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  90856. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  90857. break;
  90858. }
  90859. if (this.reflectionFresnel) {
  90860. defines.REFLECTIONFRESNEL = true;
  90861. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  90862. this._reflectionControls.x = this.reflectionAmount;
  90863. this._reflectionControls.y = this.reflectionReflectance0;
  90864. this._reflectionControls.z = this.reflectionReflectance90;
  90865. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  90866. }
  90867. else {
  90868. defines.REFLECTIONFRESNEL = false;
  90869. defines.REFLECTIONFALLOFF = false;
  90870. }
  90871. }
  90872. else {
  90873. defines.REFLECTION = false;
  90874. defines.REFLECTIONFALLOFF = false;
  90875. defines.REFLECTIONBLUR = false;
  90876. defines.REFLECTIONMAP_3D = false;
  90877. defines.REFLECTIONMAP_SPHERICAL = false;
  90878. defines.REFLECTIONMAP_PLANAR = false;
  90879. defines.REFLECTIONMAP_CUBIC = false;
  90880. defines.REFLECTIONMAP_PROJECTION = false;
  90881. defines.REFLECTIONMAP_SKYBOX = false;
  90882. defines.REFLECTIONMAP_EXPLICIT = false;
  90883. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  90884. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  90885. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  90886. defines.INVERTCUBICMAP = false;
  90887. defines.REFLECTIONMAP_OPPOSITEZ = false;
  90888. defines.LODINREFLECTIONALPHA = false;
  90889. defines.GAMMAREFLECTION = false;
  90890. }
  90891. }
  90892. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  90893. defines.USERGBCOLOR = this._useRGBColor;
  90894. defines.NOISE = this._enableNoise;
  90895. }
  90896. if (defines._areImageProcessingDirty) {
  90897. if (!this._imageProcessingConfiguration.isReady()) {
  90898. return false;
  90899. }
  90900. this._imageProcessingConfiguration.prepareDefines(defines);
  90901. }
  90902. // Misc.
  90903. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  90904. // Values that need to be evaluated on every frame
  90905. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  90906. // Attribs
  90907. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  90908. if (mesh) {
  90909. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  90910. mesh.createNormals(true);
  90911. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  90912. }
  90913. }
  90914. }
  90915. // Get correct effect
  90916. if (defines.isDirty) {
  90917. defines.markAsProcessed();
  90918. scene.resetCachedMaterial();
  90919. // Fallbacks
  90920. var fallbacks = new BABYLON.EffectFallbacks();
  90921. if (defines.FOG) {
  90922. fallbacks.addFallback(0, "FOG");
  90923. }
  90924. if (defines.POINTSIZE) {
  90925. fallbacks.addFallback(1, "POINTSIZE");
  90926. }
  90927. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  90928. if (defines.NUM_BONE_INFLUENCERS > 0) {
  90929. fallbacks.addCPUSkinningFallback(0, mesh);
  90930. }
  90931. //Attributes
  90932. var attribs = [BABYLON.VertexBuffer.PositionKind];
  90933. if (defines.NORMAL) {
  90934. attribs.push(BABYLON.VertexBuffer.NormalKind);
  90935. }
  90936. if (defines.UV1) {
  90937. attribs.push(BABYLON.VertexBuffer.UVKind);
  90938. }
  90939. if (defines.UV2) {
  90940. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90941. }
  90942. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  90943. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  90944. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  90945. "vFogInfos", "vFogColor", "pointSize",
  90946. "vClipPlane", "mBones",
  90947. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  90948. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  90949. "shadowLevel", "alpha",
  90950. "vBackgroundCenter", "vReflectionControl",
  90951. "vDiffuseInfos", "diffuseMatrix",
  90952. ];
  90953. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  90954. var uniformBuffers = ["Material", "Scene"];
  90955. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  90956. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  90957. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  90958. uniformsNames: uniforms,
  90959. uniformBuffersNames: uniformBuffers,
  90960. samplers: samplers,
  90961. defines: defines,
  90962. maxSimultaneousLights: this._maxSimultaneousLights
  90963. });
  90964. var onCompiled = function (effect) {
  90965. if (_this.onCompiled) {
  90966. _this.onCompiled(effect);
  90967. }
  90968. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  90969. };
  90970. var join = defines.toString();
  90971. subMesh.setEffect(scene.getEngine().createEffect("background", {
  90972. attributes: attribs,
  90973. uniformsNames: uniforms,
  90974. uniformBuffersNames: uniformBuffers,
  90975. samplers: samplers,
  90976. defines: join,
  90977. fallbacks: fallbacks,
  90978. onCompiled: onCompiled,
  90979. onError: this.onError,
  90980. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  90981. }, engine), defines);
  90982. this.buildUniformLayout();
  90983. }
  90984. if (!subMesh.effect || !subMesh.effect.isReady()) {
  90985. return false;
  90986. }
  90987. defines._renderId = scene.getRenderId();
  90988. this._wasPreviouslyReady = true;
  90989. return true;
  90990. };
  90991. /**
  90992. * Build the uniform buffer used in the material.
  90993. */
  90994. BackgroundMaterial.prototype.buildUniformLayout = function () {
  90995. // Order is important !
  90996. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  90997. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  90998. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  90999. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  91000. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  91001. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  91002. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  91003. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  91004. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  91005. this._uniformBuffer.addUniform("pointSize", 1);
  91006. this._uniformBuffer.addUniform("shadowLevel", 1);
  91007. this._uniformBuffer.addUniform("alpha", 1);
  91008. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  91009. this._uniformBuffer.addUniform("vReflectionControl", 4);
  91010. this._uniformBuffer.create();
  91011. };
  91012. /**
  91013. * Unbind the material.
  91014. */
  91015. BackgroundMaterial.prototype.unbind = function () {
  91016. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  91017. this._uniformBuffer.setTexture("diffuseSampler", null);
  91018. }
  91019. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  91020. this._uniformBuffer.setTexture("reflectionSampler", null);
  91021. }
  91022. _super.prototype.unbind.call(this);
  91023. };
  91024. /**
  91025. * Bind only the world matrix to the material.
  91026. * @param world The world matrix to bind.
  91027. */
  91028. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  91029. this._activeEffect.setMatrix("world", world);
  91030. };
  91031. /**
  91032. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  91033. * @param world The world matrix to bind.
  91034. * @param subMesh The submesh to bind for.
  91035. */
  91036. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  91037. var scene = this.getScene();
  91038. var defines = subMesh._materialDefines;
  91039. if (!defines) {
  91040. return;
  91041. }
  91042. var effect = subMesh.effect;
  91043. if (!effect) {
  91044. return;
  91045. }
  91046. this._activeEffect = effect;
  91047. // Matrices
  91048. this.bindOnlyWorldMatrix(world);
  91049. // Bones
  91050. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  91051. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  91052. if (mustRebind) {
  91053. this._uniformBuffer.bindToEffect(effect, "Material");
  91054. this.bindViewProjection(effect);
  91055. var reflectionTexture = this._reflectionTexture;
  91056. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  91057. // Texture uniforms
  91058. if (scene.texturesEnabled) {
  91059. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91060. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  91061. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  91062. }
  91063. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91064. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  91065. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  91066. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  91067. }
  91068. }
  91069. if (this.shadowLevel > 0) {
  91070. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  91071. }
  91072. this._uniformBuffer.updateFloat("alpha", this.alpha);
  91073. // Point size
  91074. if (this.pointsCloud) {
  91075. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  91076. }
  91077. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  91078. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  91079. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  91080. }
  91081. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  91082. // Textures
  91083. if (scene.texturesEnabled) {
  91084. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91085. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  91086. }
  91087. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91088. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  91089. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  91090. }
  91091. else if (!defines.REFLECTIONBLUR) {
  91092. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  91093. }
  91094. else {
  91095. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  91096. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  91097. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  91098. }
  91099. if (defines.REFLECTIONFRESNEL) {
  91100. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  91101. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  91102. }
  91103. }
  91104. }
  91105. // Clip plane
  91106. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  91107. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  91108. }
  91109. if (mustRebind || !this.isFrozen) {
  91110. if (scene.lightsEnabled) {
  91111. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  91112. }
  91113. // View
  91114. this.bindView(effect);
  91115. // Fog
  91116. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  91117. // image processing
  91118. this._imageProcessingConfiguration.bind(this._activeEffect);
  91119. }
  91120. this._uniformBuffer.update();
  91121. this._afterBind(mesh);
  91122. };
  91123. /**
  91124. * Dispose the material.
  91125. * @param forceDisposeEffect Force disposal of the associated effect.
  91126. * @param forceDisposeTextures Force disposal of the associated textures.
  91127. */
  91128. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  91129. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  91130. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  91131. if (forceDisposeTextures) {
  91132. if (this.diffuseTexture) {
  91133. this.diffuseTexture.dispose();
  91134. }
  91135. if (this.reflectionTexture) {
  91136. this.reflectionTexture.dispose();
  91137. }
  91138. }
  91139. this._renderTargets.dispose();
  91140. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  91141. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  91142. }
  91143. _super.prototype.dispose.call(this, forceDisposeEffect);
  91144. };
  91145. /**
  91146. * Clones the material.
  91147. * @param name The cloned name.
  91148. * @returns The cloned material.
  91149. */
  91150. BackgroundMaterial.prototype.clone = function (name) {
  91151. var _this = this;
  91152. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  91153. };
  91154. /**
  91155. * Serializes the current material to its JSON representation.
  91156. * @returns The JSON representation.
  91157. */
  91158. BackgroundMaterial.prototype.serialize = function () {
  91159. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  91160. serializationObject.customType = "BABYLON.BackgroundMaterial";
  91161. return serializationObject;
  91162. };
  91163. /**
  91164. * Gets the class name of the material
  91165. * @returns "BackgroundMaterial"
  91166. */
  91167. BackgroundMaterial.prototype.getClassName = function () {
  91168. return "BackgroundMaterial";
  91169. };
  91170. /**
  91171. * Parse a JSON input to create back a background material.
  91172. * @param source The JSON data to parse
  91173. * @param scene The scene to create the parsed material in
  91174. * @param rootUrl The root url of the assets the material depends upon
  91175. * @returns the instantiated BackgroundMaterial.
  91176. */
  91177. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  91178. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  91179. };
  91180. /**
  91181. * Standard reflectance value at parallel view angle.
  91182. */
  91183. BackgroundMaterial.StandardReflectance0 = 0.05;
  91184. /**
  91185. * Standard reflectance value at grazing angle.
  91186. */
  91187. BackgroundMaterial.StandardReflectance90 = 0.5;
  91188. __decorate([
  91189. BABYLON.serializeAsColor3()
  91190. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  91191. __decorate([
  91192. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91193. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  91194. __decorate([
  91195. BABYLON.serialize()
  91196. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  91197. __decorate([
  91198. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91199. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  91200. __decorate([
  91201. BABYLON.serializeAsColor3()
  91202. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  91203. __decorate([
  91204. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91205. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  91206. __decorate([
  91207. BABYLON.serialize()
  91208. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  91209. __decorate([
  91210. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91211. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  91212. __decorate([
  91213. BABYLON.serializeAsColor3()
  91214. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  91215. __decorate([
  91216. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91217. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  91218. __decorate([
  91219. BABYLON.serialize()
  91220. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  91221. __decorate([
  91222. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91223. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  91224. __decorate([
  91225. BABYLON.serializeAsTexture()
  91226. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  91227. __decorate([
  91228. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91229. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  91230. __decorate([
  91231. BABYLON.serialize()
  91232. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  91233. __decorate([
  91234. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91235. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  91236. __decorate([
  91237. BABYLON.serializeAsTexture()
  91238. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  91239. __decorate([
  91240. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91241. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  91242. __decorate([
  91243. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91244. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  91245. __decorate([
  91246. BABYLON.serialize()
  91247. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  91248. __decorate([
  91249. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91250. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  91251. __decorate([
  91252. BABYLON.serialize()
  91253. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  91254. __decorate([
  91255. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91256. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  91257. __decorate([
  91258. BABYLON.serializeAsVector3()
  91259. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  91260. __decorate([
  91261. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91262. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  91263. __decorate([
  91264. BABYLON.serialize()
  91265. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  91266. __decorate([
  91267. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91268. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  91269. __decorate([
  91270. BABYLON.serialize()
  91271. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  91272. __decorate([
  91273. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91274. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  91275. __decorate([
  91276. BABYLON.serialize()
  91277. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  91278. __decorate([
  91279. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91280. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  91281. __decorate([
  91282. BABYLON.serialize()
  91283. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  91284. __decorate([
  91285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91286. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  91287. __decorate([
  91288. BABYLON.serialize()
  91289. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  91290. __decorate([
  91291. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91292. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  91293. __decorate([
  91294. BABYLON.serialize()
  91295. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  91296. __decorate([
  91297. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91298. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  91299. __decorate([
  91300. BABYLON.serialize()
  91301. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  91302. __decorate([
  91303. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91304. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  91305. __decorate([
  91306. BABYLON.serialize()
  91307. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  91308. __decorate([
  91309. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91310. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  91311. __decorate([
  91312. BABYLON.serialize()
  91313. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  91314. __decorate([
  91315. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91316. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  91317. __decorate([
  91318. BABYLON.serializeAsImageProcessingConfiguration()
  91319. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  91320. return BackgroundMaterial;
  91321. }(BABYLON.PushMaterial));
  91322. BABYLON.BackgroundMaterial = BackgroundMaterial;
  91323. })(BABYLON || (BABYLON = {}));
  91324. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  91325. var __assign = (this && this.__assign) || Object.assign || function(t) {
  91326. for (var s, i = 1, n = arguments.length; i < n; i++) {
  91327. s = arguments[i];
  91328. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  91329. t[p] = s[p];
  91330. }
  91331. return t;
  91332. };
  91333. var BABYLON;
  91334. (function (BABYLON) {
  91335. /**
  91336. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  91337. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  91338. * It also helps with the default setup of your imageProcessing configuration.
  91339. */
  91340. var EnvironmentHelper = /** @class */ (function () {
  91341. /**
  91342. * constructor
  91343. * @param options
  91344. * @param scene The scene to add the material to
  91345. */
  91346. function EnvironmentHelper(options, scene) {
  91347. var _this = this;
  91348. this._errorHandler = function (message, exception) {
  91349. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  91350. };
  91351. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  91352. this._scene = scene;
  91353. this.onErrorObservable = new BABYLON.Observable();
  91354. this._setupBackground();
  91355. this._setupImageProcessing();
  91356. }
  91357. /**
  91358. * Creates the default options for the helper.
  91359. */
  91360. EnvironmentHelper._getDefaultOptions = function () {
  91361. return {
  91362. createGround: true,
  91363. groundSize: 15,
  91364. groundTexture: this._groundTextureCDNUrl,
  91365. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  91366. groundOpacity: 0.9,
  91367. enableGroundShadow: true,
  91368. groundShadowLevel: 0.5,
  91369. enableGroundMirror: false,
  91370. groundMirrorSizeRatio: 0.3,
  91371. groundMirrorBlurKernel: 64,
  91372. groundMirrorAmount: 1,
  91373. groundMirrorFresnelWeight: 1,
  91374. groundMirrorFallOffDistance: 0,
  91375. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  91376. groundYBias: 0.00001,
  91377. createSkybox: true,
  91378. skyboxSize: 20,
  91379. skyboxTexture: this._skyboxTextureCDNUrl,
  91380. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  91381. backgroundYRotation: 0,
  91382. sizeAuto: true,
  91383. rootPosition: BABYLON.Vector3.Zero(),
  91384. setupImageProcessing: true,
  91385. environmentTexture: this._environmentTextureCDNUrl,
  91386. cameraExposure: 0.8,
  91387. cameraContrast: 1.2,
  91388. toneMappingEnabled: true,
  91389. };
  91390. };
  91391. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  91392. /**
  91393. * Gets the root mesh created by the helper.
  91394. */
  91395. get: function () {
  91396. return this._rootMesh;
  91397. },
  91398. enumerable: true,
  91399. configurable: true
  91400. });
  91401. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  91402. /**
  91403. * Gets the skybox created by the helper.
  91404. */
  91405. get: function () {
  91406. return this._skybox;
  91407. },
  91408. enumerable: true,
  91409. configurable: true
  91410. });
  91411. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  91412. /**
  91413. * Gets the skybox texture created by the helper.
  91414. */
  91415. get: function () {
  91416. return this._skyboxTexture;
  91417. },
  91418. enumerable: true,
  91419. configurable: true
  91420. });
  91421. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  91422. /**
  91423. * Gets the skybox material created by the helper.
  91424. */
  91425. get: function () {
  91426. return this._skyboxMaterial;
  91427. },
  91428. enumerable: true,
  91429. configurable: true
  91430. });
  91431. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  91432. /**
  91433. * Gets the ground mesh created by the helper.
  91434. */
  91435. get: function () {
  91436. return this._ground;
  91437. },
  91438. enumerable: true,
  91439. configurable: true
  91440. });
  91441. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  91442. /**
  91443. * Gets the ground texture created by the helper.
  91444. */
  91445. get: function () {
  91446. return this._groundTexture;
  91447. },
  91448. enumerable: true,
  91449. configurable: true
  91450. });
  91451. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  91452. /**
  91453. * Gets the ground mirror created by the helper.
  91454. */
  91455. get: function () {
  91456. return this._groundMirror;
  91457. },
  91458. enumerable: true,
  91459. configurable: true
  91460. });
  91461. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  91462. /**
  91463. * Gets the ground mirror render list to helps pushing the meshes
  91464. * you wish in the ground reflection.
  91465. */
  91466. get: function () {
  91467. if (this._groundMirror) {
  91468. return this._groundMirror.renderList;
  91469. }
  91470. return null;
  91471. },
  91472. enumerable: true,
  91473. configurable: true
  91474. });
  91475. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  91476. /**
  91477. * Gets the ground material created by the helper.
  91478. */
  91479. get: function () {
  91480. return this._groundMaterial;
  91481. },
  91482. enumerable: true,
  91483. configurable: true
  91484. });
  91485. /**
  91486. * Updates the background according to the new options
  91487. * @param options
  91488. */
  91489. EnvironmentHelper.prototype.updateOptions = function (options) {
  91490. var newOptions = __assign({}, this._options, options);
  91491. if (this._ground && !newOptions.createGround) {
  91492. this._ground.dispose();
  91493. this._ground = null;
  91494. }
  91495. if (this._groundMaterial && !newOptions.createGround) {
  91496. this._groundMaterial.dispose();
  91497. this._groundMaterial = null;
  91498. }
  91499. if (this._groundTexture) {
  91500. if (this._options.groundTexture != newOptions.groundTexture) {
  91501. this._groundTexture.dispose();
  91502. this._groundTexture = null;
  91503. }
  91504. }
  91505. if (this._skybox && !newOptions.createSkybox) {
  91506. this._skybox.dispose();
  91507. this._skybox = null;
  91508. }
  91509. if (this._skyboxMaterial && !newOptions.createSkybox) {
  91510. this._skyboxMaterial.dispose();
  91511. this._skyboxMaterial = null;
  91512. }
  91513. if (this._skyboxTexture) {
  91514. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  91515. this._skyboxTexture.dispose();
  91516. this._skyboxTexture = null;
  91517. }
  91518. }
  91519. if (this._groundMirror && !newOptions.enableGroundMirror) {
  91520. this._groundMirror.dispose();
  91521. this._groundMirror = null;
  91522. }
  91523. if (this._scene.environmentTexture) {
  91524. if (this._options.environmentTexture != newOptions.environmentTexture) {
  91525. this._scene.environmentTexture.dispose();
  91526. }
  91527. }
  91528. this._options = newOptions;
  91529. this._setupBackground();
  91530. this._setupImageProcessing();
  91531. };
  91532. /**
  91533. * Sets the primary color of all the available elements.
  91534. * @param color
  91535. */
  91536. EnvironmentHelper.prototype.setMainColor = function (color) {
  91537. if (this.groundMaterial) {
  91538. this.groundMaterial.primaryColor = color;
  91539. }
  91540. if (this.skyboxMaterial) {
  91541. this.skyboxMaterial.primaryColor = color;
  91542. }
  91543. if (this.groundMirror) {
  91544. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  91545. }
  91546. };
  91547. /**
  91548. * Setup the image processing according to the specified options.
  91549. */
  91550. EnvironmentHelper.prototype._setupImageProcessing = function () {
  91551. if (this._options.setupImageProcessing) {
  91552. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  91553. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  91554. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  91555. this._setupEnvironmentTexture();
  91556. }
  91557. };
  91558. /**
  91559. * Setup the environment texture according to the specified options.
  91560. */
  91561. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  91562. if (this._scene.environmentTexture) {
  91563. return;
  91564. }
  91565. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  91566. this._scene.environmentTexture = this._options.environmentTexture;
  91567. return;
  91568. }
  91569. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  91570. this._scene.environmentTexture = environmentTexture;
  91571. };
  91572. /**
  91573. * Setup the background according to the specified options.
  91574. */
  91575. EnvironmentHelper.prototype._setupBackground = function () {
  91576. if (!this._rootMesh) {
  91577. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  91578. }
  91579. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  91580. var sceneSize = this._getSceneSize();
  91581. if (this._options.createGround) {
  91582. this._setupGround(sceneSize);
  91583. this._setupGroundMaterial();
  91584. this._setupGroundDiffuseTexture();
  91585. if (this._options.enableGroundMirror) {
  91586. this._setupGroundMirrorTexture(sceneSize);
  91587. }
  91588. this._setupMirrorInGroundMaterial();
  91589. }
  91590. if (this._options.createSkybox) {
  91591. this._setupSkybox(sceneSize);
  91592. this._setupSkyboxMaterial();
  91593. this._setupSkyboxReflectionTexture();
  91594. }
  91595. this._rootMesh.position.x = sceneSize.rootPosition.x;
  91596. this._rootMesh.position.z = sceneSize.rootPosition.z;
  91597. this._rootMesh.position.y = sceneSize.rootPosition.y;
  91598. };
  91599. /**
  91600. * Get the scene sizes according to the setup.
  91601. */
  91602. EnvironmentHelper.prototype._getSceneSize = function () {
  91603. var _this = this;
  91604. var groundSize = this._options.groundSize;
  91605. var skyboxSize = this._options.skyboxSize;
  91606. var rootPosition = this._options.rootPosition;
  91607. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  91608. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  91609. }
  91610. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  91611. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  91612. });
  91613. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  91614. if (this._options.sizeAuto) {
  91615. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  91616. this._scene.activeCamera.upperRadiusLimit) {
  91617. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  91618. skyboxSize = groundSize;
  91619. }
  91620. var sceneDiagonalLenght = sceneDiagonal.length();
  91621. if (sceneDiagonalLenght > groundSize) {
  91622. groundSize = sceneDiagonalLenght * 2;
  91623. skyboxSize = groundSize;
  91624. }
  91625. // 10 % bigger.
  91626. groundSize *= 1.1;
  91627. skyboxSize *= 1.5;
  91628. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  91629. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  91630. }
  91631. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  91632. };
  91633. /**
  91634. * Setup the ground according to the specified options.
  91635. */
  91636. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  91637. var _this = this;
  91638. if (!this._ground) {
  91639. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  91640. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  91641. this._ground.parent = this._rootMesh;
  91642. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  91643. }
  91644. this._ground.receiveShadows = this._options.enableGroundShadow;
  91645. };
  91646. /**
  91647. * Setup the ground material according to the specified options.
  91648. */
  91649. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  91650. if (!this._groundMaterial) {
  91651. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  91652. }
  91653. this._groundMaterial.alpha = this._options.groundOpacity;
  91654. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  91655. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  91656. this._groundMaterial.primaryLevel = 1;
  91657. this._groundMaterial.primaryColor = this._options.groundColor;
  91658. this._groundMaterial.secondaryLevel = 0;
  91659. this._groundMaterial.tertiaryLevel = 0;
  91660. this._groundMaterial.useRGBColor = false;
  91661. this._groundMaterial.enableNoise = true;
  91662. if (this._ground) {
  91663. this._ground.material = this._groundMaterial;
  91664. }
  91665. };
  91666. /**
  91667. * Setup the ground diffuse texture according to the specified options.
  91668. */
  91669. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  91670. if (!this._groundMaterial) {
  91671. return;
  91672. }
  91673. if (this._groundTexture) {
  91674. return;
  91675. }
  91676. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  91677. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  91678. return;
  91679. }
  91680. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  91681. diffuseTexture.gammaSpace = false;
  91682. diffuseTexture.hasAlpha = true;
  91683. this._groundMaterial.diffuseTexture = diffuseTexture;
  91684. };
  91685. /**
  91686. * Setup the ground mirror texture according to the specified options.
  91687. */
  91688. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  91689. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91690. if (!this._groundMirror) {
  91691. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  91692. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  91693. this._groundMirror.anisotropicFilteringLevel = 1;
  91694. this._groundMirror.wrapU = wrapping;
  91695. this._groundMirror.wrapV = wrapping;
  91696. this._groundMirror.gammaSpace = false;
  91697. if (this._groundMirror.renderList) {
  91698. for (var i = 0; i < this._scene.meshes.length; i++) {
  91699. var mesh = this._scene.meshes[i];
  91700. if (mesh !== this._ground &&
  91701. mesh !== this._skybox &&
  91702. mesh !== this._rootMesh) {
  91703. this._groundMirror.renderList.push(mesh);
  91704. }
  91705. }
  91706. }
  91707. }
  91708. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  91709. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  91710. };
  91711. /**
  91712. * Setup the ground to receive the mirror texture.
  91713. */
  91714. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  91715. if (this._groundMaterial) {
  91716. this._groundMaterial.reflectionTexture = this._groundMirror;
  91717. this._groundMaterial.reflectionFresnel = true;
  91718. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  91719. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  91720. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  91721. }
  91722. };
  91723. /**
  91724. * Setup the skybox according to the specified options.
  91725. */
  91726. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  91727. var _this = this;
  91728. if (!this._skybox) {
  91729. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  91730. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  91731. }
  91732. this._skybox.parent = this._rootMesh;
  91733. };
  91734. /**
  91735. * Setup the skybox material according to the specified options.
  91736. */
  91737. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  91738. if (!this._skybox) {
  91739. return;
  91740. }
  91741. if (!this._skyboxMaterial) {
  91742. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  91743. }
  91744. this._skyboxMaterial.useRGBColor = false;
  91745. this._skyboxMaterial.primaryLevel = 1;
  91746. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  91747. this._skyboxMaterial.secondaryLevel = 0;
  91748. this._skyboxMaterial.tertiaryLevel = 0;
  91749. this._skyboxMaterial.enableNoise = true;
  91750. this._skybox.material = this._skyboxMaterial;
  91751. };
  91752. /**
  91753. * Setup the skybox reflection texture according to the specified options.
  91754. */
  91755. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  91756. if (!this._skyboxMaterial) {
  91757. return;
  91758. }
  91759. if (this._skyboxTexture) {
  91760. return;
  91761. }
  91762. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  91763. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  91764. return;
  91765. }
  91766. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  91767. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  91768. this._skyboxTexture.gammaSpace = false;
  91769. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  91770. };
  91771. /**
  91772. * Dispose all the elements created by the Helper.
  91773. */
  91774. EnvironmentHelper.prototype.dispose = function () {
  91775. if (this._groundMaterial) {
  91776. this._groundMaterial.dispose(true, true);
  91777. }
  91778. if (this._skyboxMaterial) {
  91779. this._skyboxMaterial.dispose(true, true);
  91780. }
  91781. this._rootMesh.dispose(false);
  91782. };
  91783. /**
  91784. * Default ground texture URL.
  91785. */
  91786. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  91787. /**
  91788. * Default skybox texture URL.
  91789. */
  91790. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  91791. /**
  91792. * Default environment texture URL.
  91793. */
  91794. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  91795. return EnvironmentHelper;
  91796. }());
  91797. BABYLON.EnvironmentHelper = EnvironmentHelper;
  91798. })(BABYLON || (BABYLON = {}));
  91799. //# sourceMappingURL=babylon.environmentHelper.js.map
  91800. var BABYLON;
  91801. (function (BABYLON) {
  91802. /**
  91803. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  91804. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  91805. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  91806. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  91807. */
  91808. var VideoDome = /** @class */ (function (_super) {
  91809. __extends(VideoDome, _super);
  91810. /**
  91811. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  91812. * @param name Element's name, child elements will append suffixes for their own names.
  91813. * @param urlsOrVideo
  91814. * @param options An object containing optional or exposed sub element properties:
  91815. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  91816. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  91817. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  91818. * @param options **loop=true** Automatically loop video on end.
  91819. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  91820. */
  91821. function VideoDome(name, urlsOrVideo, options, scene) {
  91822. var _this = _super.call(this, name, scene) || this;
  91823. // set defaults and manage values
  91824. name = name || "videoDome";
  91825. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  91826. options.clickToPlay = Boolean(options.clickToPlay);
  91827. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  91828. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  91829. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  91830. // create
  91831. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  91832. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  91833. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  91834. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  91835. flat: false,
  91836. radius: options.size,
  91837. subdivisions: options.resolution,
  91838. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  91839. }, scene);
  91840. // configure material
  91841. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  91842. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  91843. material.reflectionTexture = _this._videoTexture;
  91844. material.useEquirectangularFOV = true;
  91845. material.fovMultiplier = 1.0;
  91846. // configure mesh
  91847. _this._mesh.material = material;
  91848. _this._mesh.parent = _this;
  91849. // optional configuration
  91850. if (options.clickToPlay) {
  91851. scene.onPointerUp = function () {
  91852. _this._videoTexture.video.play();
  91853. };
  91854. }
  91855. return _this;
  91856. }
  91857. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  91858. /**
  91859. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  91860. * Also see the options.resolution property.
  91861. */
  91862. get: function () {
  91863. return this._material.fovMultiplier;
  91864. },
  91865. set: function (value) {
  91866. this._material.fovMultiplier = value;
  91867. },
  91868. enumerable: true,
  91869. configurable: true
  91870. });
  91871. /**
  91872. * Releases resources associated with this node.
  91873. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  91874. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  91875. */
  91876. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  91877. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  91878. this._videoTexture.dispose();
  91879. this._mesh.dispose();
  91880. this._material.dispose();
  91881. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  91882. };
  91883. return VideoDome;
  91884. }(BABYLON.Node));
  91885. BABYLON.VideoDome = VideoDome;
  91886. })(BABYLON || (BABYLON = {}));
  91887. //# sourceMappingURL=babylon.videoDome.js.map
  91888. 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\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<0.4)\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)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\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*vRefractionInfos.x;\n#endif\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*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\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*vReflectionInfos.x;\n#endif\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)\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#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\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\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(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).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(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).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=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*=vReflectionInfos.x;\nenvironmentRadiance*=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(reflectionCoords,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*=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\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\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;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef 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\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\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\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}","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 vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*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); \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 vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\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\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+vec4(offset*size,0.,0.));\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 vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float angle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,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;\noutColor=vec4(0.,0.,0.,0.);\noutSize=0.;\noutDirection=direction;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*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(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h/height;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (angle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-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;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\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\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{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,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;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\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;\ngl_FragColor=original;\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);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\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}\ngl_FragColor=texture2D(textureSampler,posM,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}\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{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\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\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D originalSampler;\nuniform sampler2D circleOfConfusionSampler;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n\nvarying vec2 vUV;\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(originalSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred1=texture2D(textureSampler,vUV);\ngl_FragColor=mix(original,blurred1,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(textureSampler,vUV); \nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred2,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nvec4 blurred3=texture2D(textureSampler,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred1,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred1,blurred2,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred2,blurred3,(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;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,coc,1.0);\n}\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\n#ifdef GRAIN\nvec2 seed=vUV*(grainAnimatedSeed);\nfloat grain=dither(seed,grainVarianceAmount);\n\nfloat lum=getLuminance(result.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\nresult.rgb+=grain*grainAmount;\nresult.rgb=max(result.rgb,0.0);\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\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{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,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\nvec3 reflectionColor=vec3(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).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=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*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\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,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#ifndef GRAIN \n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\n#endif\ngl_FragColor=color;\n}\n"};
  91889. 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}","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;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\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=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\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=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\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\n#ifdef GRAIN\nuniform float grainVarianceAmount;\nuniform float grainAnimatedSeed;\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,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,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,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)\n{\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 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\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,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);\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,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);\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,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);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\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\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\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;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\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 vSecondaryColor;\nuniform vec4 vTertiaryColor;\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};"};
  91890. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  91891. globalObject["BABYLON"] = BABYLON
  91892. return BABYLON;
  91893. });